简体   繁体   English

在Android中缩小图片文件大小(图片类型未知)

[英]Reduce image file size in Android (image type unknown)

I want to let the user choose how much they want to reduce the image file size by, could be low, medium or high then upload the image to a server That part is easy. 我想让用户选择要减少图像文件大小的大小,可以是低,中或高,然后将图像上传到服务器。这部分很容易。

Next part is the actual reduction of file size. 下一部分是文件大小的实际减少。 I'm getting the image URI, I want to reduce the file image file size, the image type could be png, jpg or something else. 我正在获取图像URI,我想减小文件图像文件的大小,图像类型可以是png,jpg或其他。

I'm aware of Bitmap.compress() , is this the only way to implement or is there an existing open source library? 我知道Bitmap.compress() ,这是唯一的实现方法还是现有的开源库?

Bitmap bitmap;
bitmap = MyBitmapFactory.decodeFile(PATHTOPICT, UPLOAD_REQUIRED_SIZE);
if (bitmap != null) {
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

with the method (found with google): 与方法(与谷歌找到):

public static Bitmap decodeFile(String filePath, final int REQUIRED_SIZE) {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp <= REQUIRED_SIZE && height_tmp <= REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}

if something get NULL, its no image/ . 如果某些内容为NULL,则没有图像 scale by power 2 is recommended!!! 推荐按功率2缩放!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM