Android调整作为base64字符串接收的大图像

标签 android image base64 bitmapfactory

我在 android 中调整图像大小时遇到​​一些问题。 我有一个 base64 字符串(我没有文件或 url,只有字符串),到目前为止,我一尝试解码它就遇到内存不足异常。

public String resizeBase64Image(String base64image){

    byte [] encodeByte=Base64.decode(base64image,Base64.DEFAULT); //out of memory exception...

    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inPurgeable = true;
    Bitmap image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length,options);

    image = Bitmap.createScaledBitmap(image, IMG_WIDTH, IMG_HEIGHT, false);

    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] newbytes=baos.toByteArray();

    return Base64.encodeToString(newbytes, Base64.DEFAULT);

}

有人有想法吗?

最佳答案

我花了一段时间才回到这个项目,但我终于找到了解决我的问题的方法。 首先,我需要修改 Manfest 的应用程序标签以添加 largeHeap=:true":

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:largeHeap="true" >

使用垃圾收集器帮助很大。

public String resizeBase64Image(String base64image){
    byte [] encodeByte=Base64.decode(base64image.getBytes(),Base64.DEFAULT); 
    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inPurgeable = true;
    Bitmap image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length,options);


    if(image.getHeight() <= 400 && image.getWidth() <= 400){
        return base64image;
    }
    image = Bitmap.createScaledBitmap(image, IMG_WIDTH, IMG_HEIGHT, false);

    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG,100, baos);

    byte [] b=baos.toByteArray();
    System.gc();
    return Base64.encodeToString(b, Base64.NO_WRAP);

}   

关于Android调整作为base64字符串接收的大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27416618/

相关文章:

android - 为 android 商店签署 kivy 应用程序时出错

java - 如何导出带有图像和声音的可运行 Jar?

java - 在屏幕上重复加载/删除多个图像的最佳方法

java - Java 中的 Base64 Ascii 编码

javascript - 从 Base64 编码的 midi 进行 MidiConvert

android - 将 GCM 注册 ID 传递给合作伙伴服务器是否安全

java - 从 Firebase 检索数据但 snaptshop.get 返回 null

android - 未应用操作栏样式

php - 从 Android 上传图像到服务器不起作用

python - 使用 xlwt 在 excel 上插入图像 base 64