Android,压缩图像

3
我正在通过wifi或移动网络将图像发送到服务器进行存储和再次检索。我已经完成了这个过程,但由于相机拍摄的图像大小,我的应用程序变得很慢。需要指出的是,我是从相册中打开并获取图片,并非直接从应用程序中获取图片。我注意到来自whatsapp的图片已被压缩到约100kb左右。

目前,我的代码将文件转换为字节,然后发送它。以下是将文件转换为字节的方法:

private void toBytes(String filePath){
    try{
        File file = new File(filePath);
        InputStream is = new BufferedInputStream(new FileInputStream(file));  
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        bytes = new byte[(int) filePath.length()];
        int bytes_read;
        while((bytes_read = is.read(bytes, 0, bytes.length)) != -1){
            buffer.write(bytes, 0, bytes_read);
        }
        is.close();               
        bytes = buffer.toByteArray();
    }catch(Exception err){
        Toast.makeText(getApplicationContext(), err.toString(), Toast.LENGTH_SHORT).show();
    }
}

所以我的问题是,在发送之前如何压缩我的图像?另外,当应用程序使用该图像时,我不需要图像保留高像素计数,因为它只会占用设备屏幕的一半。
感谢您提供的任何帮助。

也许这个链接可以帮到你https://dev59.com/tXE85IYBdhLWcg3wikO- - Rohit Sharma
可能是在Android中压缩图像的重复问题。 - Ishtar
2个回答

3

1

尝试使用以下方法:

    //decodes image and scales it to reduce memory consumption
    //NOTE: if the image has dimensions which exceed int width and int height
    //its dimensions will be altered.
    private Bitmap decodeToLowResImage(byte [] b, int width, int height) {
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o);

            //The new size we want to scale to
            final int REQUIRED_SIZE_WIDTH=(int)(width*0.7);
            final int REQUIRED_SIZE_HEIGHT=(int)(height*0.7);

            //Find the correct scale value. It should be the power of 2.
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE_WIDTH || height_tmp/2<REQUIRED_SIZE_HEIGHT)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o2);
        } catch (OutOfMemoryError e) {
        }
        return null;
    }

1
你能解释一下为什么在你的解决方案中要将所需宽度和高度乘以0.7吗?谢谢。 - thom_nic
1
嗯,我现在会推荐这个解决方案:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html - Dhruv Gairola

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接