Android:从位图转换为 Byte[] OutOfMemory 错误

Posted

技术标签:

【中文标题】Android:从位图转换为 Byte[] OutOfMemory 错误【英文标题】:Android: conversion from bitmap to Byte[] OutOfMemory error 【发布时间】: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[] 它工作正常。 【参考方案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();

【讨论】:

此代码在 中添加清单文件

以上是关于Android:从位图转换为 Byte[] OutOfMemory 错误的主要内容,如果未能解决你的问题,请参考以下文章

android从onPreviewFrame获取像素数据转换为位图

VB.net 如何将数据转换为位图(Bitmap)所需要的byte()数组?急!!!!

准备位图 byte[] 数据以传递给 jni

将预览帧转换为位图

Android将base64编码的字符串转换为图像视图

Android - Grow Heap (Frag Case) - Byte Allocation.. 不加载任何位图