【问题标题】:Android - Converting compressed Bitmap (gzip) to Base64 causing data lossAndroid - 将压缩位图 (gzip) 转换为 Base64 导致数据丢失
【发布时间】:2014-10-30 04:53:30
【问题描述】:

我正在尝试使用 gzip 将位图转换为 base64。

我尝试了here 的解决方案,但出现此错误GZIP 无法解析或不是字段

我下面的解决方案正在运行,但图像在底部被剪切

这是我的代码:

        Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg");
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        GZIPOutputStream gzipOstream=null;
        try {
            gzipOstream=new GZIPOutputStream(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100,  gzipOstream);
        byte[] byteArry=stream.toByteArray();
        String encodedImage = Base64.encodeToString(byteArry,  Base64.NO_WRAP);
        try {
            gzipOstream.close();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } 

此代码会使图像丢失数据还是服务器端的东西?

【问题讨论】:

    标签: android bitmap base64 gzip


    【解决方案1】:

    在调用mBitmap.compress(); 之后调用gzipOstream.flush(); 这保证了输出字节流包含所有内容。然后您的toByteArray(); 将获得当前缺失的数据。

    试试这个:

    Bitmap myBitmap = BitmapFactory.decodeFile("\path\to\file.jpg");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        GZIPOutputStream gzipOstream = null;
        try {
            gzipOstream = new GZIPOutputStream(stream);
            myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, gzipOstream);
            gzipOstream.flush();
        } finally {
            gzipOstream.close();
            stream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
        stream = null;
    }
    if(stream != null) {
        byte[] byteArry=stream.toByteArray();
        String encodedImage = Base64.encodeToString(byteArry, Base64.NO_WRAP);
        // do something with encodedImage
    }
    

    【讨论】:

    • 这对我不起作用。图像仍然变灰
    • 你是我的英雄 :) 效果很好。非常感谢。
    • 欢迎您。感谢@TheIronMarx 的格式化。我批准了。当我编辑代码时,我正在火车上;)手机很糟糕。我正要编辑编辑它,你也会打败我;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多