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

标签 android image-processing bitmap 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 并作为 MMS 发送,我不确定,但我认为 JPEG 是 MMS 中所有设备都支持的唯一格式。接收器将打开图像并将其转换回 png 而不会丢失数据。

最佳答案

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

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

quality: Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting

关于android - 位图压缩 PNG -> JPEG,在 Android 中反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14604031/

相关文章:

android - 如何修复截击测试编译

java - 无法解析方法 setOnChildClickListener

android - Kotlin Android-如何实现 CheckBox.OnCheckedChangeListener?

c++ - 组合图像中的重叠组

image-processing - 一种快速细化算法

vba - 如何使用 pastepecial 将图表作为位图粘贴到 vba 中的另一张纸上

android - 如何在 Android 上不使用 createBitmap() 和 copy() 将位图复制到另一个位图?

android - Viewpager 与 SwipeRefreshLayout 刷新时图标不会消失

java - Android: 有没有办法将 byte[] 图像拆分成两个然后拉伸(stretch)它们?

android - 查看带有大量图像的分页,它甚至可以工作吗?