gpt4 book ai didi

android - 如何减小图像文件的大小

转载 作者:行者123 更新时间:2023-11-29 15:39:21 28 4
gpt4 key购买 nike

我在上传之前使用这个功能来减小图像的大小,但是使用下面的方法我的文件大小增加了

在使用下面的代码之前我的文件大小---> 157684

使用此代码后我的文件大小 ----->177435

请问有人能帮我在上传到服务器之前如何减小文件大小

代码:

public File saveBitmapToFile(File file){
try {

// BitmapFactory options to downsize the image
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inSampleSize = 6;
// factor of downsizing the image

FileInputStream inputStream = new FileInputStream(file);
//Bitmap selectedBitmap = null;
BitmapFactory.decodeStream(inputStream, null, o);
inputStream.close();

// The new size we want to scale to
final int REQUIRED_SIZE=75;

// Find the correct scale value. It should be the power of 2.
int scale = 1;
while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
o.outHeight / scale / 2 >= REQUIRED_SIZE) {
scale *= 2;
}

BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
inputStream = new FileInputStream(file);

Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2);
inputStream.close();

// here i override the original image file
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);

selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100 , outputStream);

return file;
} catch (Exception e) {
return null;
}
}

最佳答案

这是我用来在不压缩的情况下减小图像大小的方法:

public static Bitmap getResizedBitmap(Bitmap bitmap, int newWidth, int newHeight) {
Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);

float ratioX = newWidth / (float) bitmap.getWidth();
float ratioY = newHeight / (float) bitmap.getHeight();
float middleX = newWidth / 2.0f;
float middleY = newHeight / 2.0f;

Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

return scaledBitmap;
}

您只需输入正确的新高度和宽度即可满足您的需要

关于android - 如何减小图像文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653980/

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