【问题标题】:Image encoding and Decoding using Base64 in android application在android应用程序中使用Base64进行图像编码和解码
【发布时间】:2012-07-24 08:47:24
【问题描述】:

在我的应用程序中,我在将图像编码和解码为字符串并将其传递给 Web 服务时遇到了一个小问题。 获取位图图像后,我将其转换为 byte[] 并编码为 String 值,但在某些情况下它会显示错误,我不知道它为什么会出现。 还有一个疑问是 Base64 类只支持将位图图像转换为字符串或任何其他可用的工具。

提前谢谢...

【问题讨论】:

  • 它显示为内存不足异常,我认为字符串不会保存那么大的字符串值是真的......

标签: android android-widget


【解决方案1】:

在 OutOfMemoryError 的情况下,下面的代码可以帮助我。

public String BitMapToString(Bitmap bitmap){
        ByteArrayOutputStream baos=new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
        byte [] b=baos.toByteArray();
        String temp=null;
        try{
        System.gc();
        temp=Base64.encodeToString(b, Base64.DEFAULT);
        }catch(Exception e){
            e.printStackTrace();
        }catch(OutOfMemoryError e){
            baos=new  ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,50, baos);
            b=baos.toByteArray();
            temp=Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("EWN", "Out of memory error catched");
        }
        return temp;
  }

基本上我所做的是:我捕获 OutofMemoryError 并在该捕获块中将其大小调整 50%,然后将其编码为字符串。

【讨论】:

  • @Sri 对,它会调整图像的大小,因为我必须编码大图像(大约 3-5 mb)并且需要发送到服务器。
【解决方案2】:

试试我下面的项目示例代码

Bitmap bmp = (Bitmap) data.getExtras().get("data");

        img.setImageBitmap(bmp);
        btnadd.requestFocus();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

        byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
        Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                bytarray.length);

【讨论】:

  • 感谢您的支持...我也做了同样的事情还有其他工具可以做同样的事情吗?
  • 试试上面的代码 sn-p 来自我完成的项目之一..它会正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多