【问题标题】:Android: conversion from bitmap to Byte[] OutOfMemory errorAndroid:从位图转换为 Byte[] OutOfMemory 错误
【发布时间】:2014-06-11 09:26:39
【问题描述】:

我尝试将保存在手机存储 (.jpg) 中的图像转换为位图,然后将此位图转换为字节 [] 以将此图像上传到数据库。

public void insertData() {
        File file = new File(photoUrl);
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bytes = stream.toByteArray();
        DBConnUpdate conn = new DBConnUpdate();
        conn.execute(   "insert into test (img, name) "+
                        "values ( '"+ bytes +"', '"+ productName +"')");

    }

但由于此处出现 OutOfMemory 错误,它不起作用:

bytes = stream.toByteArray();

为什么?

【问题讨论】:

  • 不要将位图字节存储在数据库中,而是将文件路径存储在数据库中。由于字节数组太大而无法保存在 dalvik 虚拟机实例内存中,因此内存不足。
  • 我需要图像对其他设备可见。 Morover,如果我尝试直接将 .jpg 文件转换为 bit[] 它工作正常。

标签: android bitmap out-of-memory bytearray bmp


【解决方案1】:
Try This Code:-


 BitmapFactory.Options options = new BitmapFactory.Options();
                 options.inDither = false;
                 options.inJustDecodeBounds = false;
                 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                 options.inSampleSize = 1;
                 options.inPurgeable = true;
                 options.inPreferQualityOverSpeed = true;
                 options.inTempStorage=new byte[32 * 1024];

    File file = new File(photoUrl);
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
            bytes = stream.toByteArray();

【讨论】:

  • 此代码在 中添加清单文件
猜你喜欢
  • 2015-01-25
  • 2015-04-22
  • 1970-01-01
  • 2012-05-03
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
相关资源
最近更新 更多