gpt4 book ai didi

android - 将相机中的图像文件压缩到一定大小

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:07 24 4
gpt4 key购买 nike

我正在尝试压缩保存在文件中的图像。我正在尝试将文件压缩为 1MB。我尝试了几种方法,但它通常会导致 OutofMemoryError。然后我尝试使用这个解决方案,但它使位图空白。

How to compress bitmap from 10mb image from camera to 300kb beforw setting to imageview in android

这是我的代码:

    System.gc();
getActivity().getContentResolver().notifyChange(mImageTempUri, null);
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(mImageDirectory + mImageName, options);
if(bitmap == null){
howRequestFailedErrorMessage("Gambar gagal di-upload");
return;

ByteArrayOutputStream bytes = new ByteArrayOutputStream();


bitmap.compress(Bitmap.CompressFormat.JPEG, 25, bytes);
File f = new File(mImageDirectory + mImageName);
if(f.exists()){
f.delete();
}
FileOutputStream fo;

try {
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
bitmap.recycle();

最佳答案

好吧,我有自己的答案

    File f = new File(mImageDirectory + mImageName);
if(f.exists()){
f.delete();
}

int MAX_IMAGE_SIZE = 1000 * 1024;
int streamLength = MAX_IMAGE_SIZE;
int compressQuality = 105;
ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) {
try {
bmpStream.flush();//to avoid out of memory error
bmpStream.reset();
} catch (IOException e) {
e.printStackTrace();
}
compressQuality -= 5;
bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
byte[] bmpPicByteArray = bmpStream.toByteArray();
streamLength = bmpPicByteArray.length;
if(BuildConfig.DEBUG) {
Log.d("test upload", "Quality: " + compressQuality);
Log.d("test upload", "Size: " + streamLength);
}
}

FileOutputStream fo;

try {
fo = new FileOutputStream(f);
fo.write(bmpStream.toByteArray());
fo.flush();
fo.close();
} catch (IOException e) {
e.printStackTrace();
}

关于android - 将相机中的图像文件压缩到一定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28760941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com