在Android中将位图压缩从PNG格式转换为JPEG格式,反之亦然

4
我在将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";

to

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

并且

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

to

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

图像大小从585847更改为531409(在DDMS中)

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

2个回答

5

这是不可行的!一旦转换为JPG,就会丢失PNG的“无损状态”。

无论如何,PNG受到所有人的支持。

+在您的情况下,您希望接收者将其更改回PNG以检索无损图像。这意味着接收者也支持PNG。将其发送时将其更改为JPG,然后在接收时再将其更改回PNG有什么意义呢?只是多余的计算吗?


我之前认为MMS中的图片只能以JPEG格式发送,实际上我无法理解它是如何工作的,因为我没有安卓设备。感谢您的回复。 - Marcin_cyna
2
答案是:一旦你转换成JPG,你就失去了PNG的“无损状态”。所以设备是否支持并不重要。我实际上不知道MMS是否支持PNG。 - Sherif elKhatib

5

谢谢您验证我的答案,我给您+1 :) - Milos Cuculovic

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