图像处理 - 位图压缩PNG -> JPEG,反之亦然



当我从PNG转换为JPEG,然后JPEG到PNG时,我的图片大小有问题。

            public void onClick(View v) {
            String imageFileName = "/sdcard/Penguins2.png";
            File imageFile = new File(imageFileName);
            if (imageFile.exists()) {
                // Load the image from file
                myBitmap = BitmapFactory.decodeFile(imageFileName);
                // Display the image in the image viewer
                myImageView = (ImageView) findViewById(R.id.my_image_view);
                if (myImageView != null) {
                    myImageView.setImageBitmap(myBitmap);
                }
            }
        }

转换:

    private void processImage() {               
    try {
        String outputPath = "/sdcard/Penguins2.jpg";
        int quality = 100;
        FileOutputStream fileOutStr = new FileOutputStream(outputPath);
        BufferedOutputStream bufOutStr = new BufferedOutputStream(
                fileOutStr);
        myBitmap.compress(CompressFormat.JPEG, quality, bufOutStr);
        bufOutStr.flush();
        bufOutStr.close();
    } catch (FileNotFoundException exception) {
        Log.e("debug_log", exception.toString());
    } catch (IOException exception) {
        Log.e("debug_log", exception.toString());
    }
    myImageView.setImageBitmap(myBitmap);

处理完此操作后,我只需更改以下行:

String imageFileName = "/sdcard/Penguins2.png";

String imageFileName = "/sdcard/Penguins2.jpg";

String outputPath = "/sdcard/Penguins2.jpg";
(...)
myBitmap.compress(CompressFormat.JPEG, quality, bufOutStr);    

String outputPath = "/sdcard/Penguins2.png";
(...)
myBitmap.compress(CompressFormat.PNG, quality, bufOutStr);    

图像大小从585847更改为531409(以 DDMS 为单位)

我想做这样的事情,因为我想使用无损的 PNG 进行某些图像处理。然后将图像转换为 jpeg 并作为彩信发送,我不确定,但我认为 JPEG 只是彩信中所有设备支持的格式。接收器将打开图像并将其反转回 png,而不会丢失数据。

除了@Sherif elKhatib 答案之外,如果您查看文档:http://developer.android.com/reference/android/graphics/Bitmap.html#compress%28android.graphics.Bitmap.CompressFormat,%20int,%20java.io.OutputStream%29

您可以看到 PNG 图像不使用质量参数:

质量:提示压缩器,0-100。 0 表示压缩表示小尺寸,100 表示压缩以获得最高质量。某些格式,例如无损的PNG,将忽略质量设置

这是

不行的!转换为JPG后,您将失去"PNG的无损状态"。

无论如何,每个人都支持png。

+在您的情况下,您希望接收器将其更改回PNG以检索无损图像。这意味着接收器也支持 PNG。在发送之前将其更改为JPG,然后在收到时将其更改回PNG有什么意义。只是一些额外的计算?

最新更新