我使用此功能在上传之前缩小图像的大小,但使用下面的方法我的文件大小正在增加
在使用下面的代码之前我的文件大小---> 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;
}
}
答案 0 :(得分:1)
更改此行:
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 100 , outputStream);
到
int mCompressedSize = 50; // 0 is lowest and 100 original
selectedBitmap.compress(Bitmap.CompressFormat.PNG, mCompressedSize, outputStream);
希望这会有所帮助。
答案 1 :(得分:1)
这是我用来减少图像大小而不压缩的方法:
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;
}
您只需输入正确的新高度和宽度即可满足您的需求
答案 2 :(得分:1)
我们想制作图像的缩略图,因此我们需要首先使用ByteArrayOutputStream然后将其传递给Bitmap.compress()方法。
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
youBitmapImage.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
来自docs
的更多关于该功能的内容答案 3 :(得分:1)
如果输出文件较大:
这可能意味着scale
错了。并且您以100%的质量保存文件,以便它可以增长
输入文件上的压缩非常繁重,即使您缩放它,在输出上不使用压缩仍会生成更大的文件
答案 4 :(得分:0)
尝试
int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
File file = new File (imageUrl);
try {
Bitmap bitmap = BitmapFactory.decodeFile (file.getPath ());
bitmap.compress (Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream (file));
}
catch (Throwable t) {
Log.e("ERROR", "Error compressing file." + t.toString ());
t.printStackTrace ();
}