我在 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/