Rip*_*de4 5 compression android image bitmap android-bitmap
我已经实现了下面的代码来缩小图像的纵横比(通过相对于彼此成比例地减小高度/宽度)。这肯定有助于减小上传到我后端的图像的大小,但这并没有考虑到图像的分辨率。我想设置一个硬图像限制,比如 800Kb,如果图像在调整大小后大于 800Kb,则压缩到小于 800Kb 的点。
任何人都有做这样的事情的经验?我很好奇传递给 Bitmap.Compress 方法的质量参数与每个质量百分比减少的文件大小之间有什么关系 - 如果我能获得这些信息,我相信我可以达到我的目标。
提前感谢您的任何帮助,我当前的代码如下,也许它会帮助其他人在未来朝着这个方向前进。
public static void uploadImage(String url, File file, Callback callback, Context context,
IMAGE_PURPOSE purpose) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int maxWidth = 0;
int maxHeight = 0;
int maxSize = 0;
switch(purpose){
case PROFILE:
maxWidth = Constants.MAX_PROFILE_IMAGE_WIDTH;
maxHeight = Constants.MAX_PROFILE_IMAGE_HEIGHT;
maxSize = Constants.MAX_PROFILE_IMAGE_SIZE;
break;
case UPLOAD:
maxWidth = Constants.MAX_UPLOAD_IMAGE_WIDTH;
maxHeight = Constants.MAX_UPLOAD_IMAGE_HEIGHT;
maxSize = Constants.MAX_UPLOAD_IMAGE_SIZE;
break;
}
int newWidth = bitmap.getWidth();
int newHeight = bitmap.getHeight();
// Make sure the width is OK
if(bitmap.getWidth() > maxWidth){
// Find out how much the picture had to shrink to get to our max defined width
float shrinkCoeff = ((float)(bitmap.getWidth() - maxWidth) / (float)bitmap.getWidth());
newWidth = maxWidth;
// Shrink the height by the same amount to maintain aspect ratio
newHeight = bitmap.getHeight() - (int)((float)bitmap.getHeight() * shrinkCoeff);
}
// Make sure the height is OK
if(newHeight > maxHeight){
// Find out how much the picture had to shrink to get to our max defined width
float shrinkCoeff = ((newHeight - maxHeight) / newHeight);
newHeight = maxHeight;
// Shrink the width by the same amount to maintain aspect ratio
newWidth = newWidth - (int)((float)newWidth * shrinkCoeff);
}
Bitmap resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
// Get the image in bytes
ByteArrayOutputStream bos = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] imageBytes = bos.toByteArray();
// If the size on disk is too big, reduce the quality
if(imageBytes.length > maxSize){
// Compress image here to get to maxSize
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1981 次 |
| 最近记录: |