gpt4 book ai didi

android - 在Android中将位图的大小缩小到指定大小

转载 作者:可可西里 更新时间:2023-11-01 19:10:08 25 4
gpt4 key购买 nike

我想将位图的大小精确地减小到 200kb。我从 sdcard 中获取图像,将其压缩并以不同的名称再次保存到 sdcard 中的不同目录中。压缩效果很好(3 mb 的图像被压缩到大约 100 kb)。我为此编写了以下代码行:

String imagefile ="/sdcard/DCIM/100ANDRO/DSC_0530.jpg";
Bitmap bm = ShrinkBitmap(imagefile, 300, 300);

//this method compresses the image and saves into a location in sdcard
Bitmap ShrinkBitmap(String file, int width, int height){

BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);

if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}

bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
//this gives the size of the compressed image in kb
long lengthbmp = imageInByte.length / 1024;

try {
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/compressed_new.jpg"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return bitmap;
}

最佳答案

我找到了一个非常适合我的答案:

/**
* reduces the size of the image
* @param image
* @param maxSize
* @return
*/
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();

float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}

调用方法:

Bitmap converetdImage = getResizedBitmap(photo, 500);

photo 是您的位图

关于android - 在Android中将位图的大小缩小到指定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16954109/

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