繁体   English   中英

Android,压缩图像

[英]Android, Compressing an image

我通过网络通过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();
    }
}

所以我的问题是如何在发送之前压缩我的图像? 此外,我不需要图像保留高像素数,因为当应用程序使用图像时,它将只占用设备屏幕的一半。

谢谢你给予的任何帮助。

BitMap http://developer.android.com/reference/android/graphics/Bitmap.html类有一个compress方法。 但是您可能需要缩放图像createScaledBitmap ,也可以在同一个类中使用。

尝试使用以下方法:

    //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;
    }

名为SiliCompressor的Android库已经过优化,可以为您完成所有图像压缩。 Github上查看

暂无
暂无

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

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