小编典典

Android,压缩图像

java

我正在通过wifi或移动网络通过网络发送图像,以将其存储在服务器中并再次检索。我已经这样做了,但是由于相机拍摄的图像太大,这使我的应用程序变慢,只是要指出我正在打开图库并从那里拍摄照片,而不是直接从应用程序拍摄照片。我注意到,从相机和图库中获取的来自whatsapp的图像已被压缩到大约50%。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();
    }
}

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

感谢您提供的任何帮助。


阅读 243

收藏
2020-11-19

共1个答案

小编典典

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

2020-11-19