在Android中,位图压缩PNG-> JPEG,反之亦然

Mar*_*yna 4 png android jpeg bitmap image-processing

从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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

转换:

    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);
Run Code Online (Sandbox Code Playgroud)

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

String imageFileName = "/sdcard/Penguins2.png";
Run Code Online (Sandbox Code Playgroud)

String imageFileName = "/sdcard/Penguins2.jpg";
Run Code Online (Sandbox Code Playgroud)

String outputPath = "/sdcard/Penguins2.jpg";
(...)
myBitmap.compress(CompressFormat.JPEG, quality, bufOutStr);    
Run Code Online (Sandbox Code Playgroud)

String outputPath = "/sdcard/Penguins2.png";
(...)
myBitmap.compress(CompressFormat.PNG, quality, bufOutStr);    
Run Code Online (Sandbox Code Playgroud)

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

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

She*_*tib 5

这是行不通的!一旦转换为JPG,您就失去了“ PNG的无损状态”。

无论如何,所有人都支持png。

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

  • 答案是:***一旦转换为JPG,就会丢失“ PNG的无损状态”。***。因此,设备是否支持它并不重要。我实际上不知道MMS是否支持PNG。 (2认同)

Mil*_*loš 5

除了@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,将忽略质量设置