【问题标题】:How to convert image to string in Android?如何在Android中将图像转换为字符串?
【发布时间】:2016-12-30 12:21:38
【问题描述】:

It's my MySql DB 它的编码:-

public String convertBitmapToString(Bitmap bmp) {
   ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); //compress to which format you want.
        byte[] byte_arr = stream.toByteArray();
        String imageStr = Base64.encodeToString(byte_arr, 1);
        return imageStr;
}

这是解码:-

String img=o.toString();
   byte[] imageAsBytes = Base64.decode(img.getBytes(), Base64.DEFAULT);
 imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

谢谢。

【问题讨论】:

  • 那么,代码有什么问题?
  • 你是什么意思?我没有看到任何问题
  • 什么是参考?
  • 我正在使用 php 脚本从 mysql db 获取字符串,但图像视图变为白屏
  • 图像未显示在 imageview 上。

标签: android android-image


【解决方案1】:

可以这样做

private String getBase64String() {

    // give your image file url in mCurrentPhotoPath
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    // In case you want to compress your image, here it's at 40%
    bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();

    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

用于解码

private void decodeBase64AndSetImage(String completeImageData, ImageView imageView) {

    // Incase you're storing into aws or other places where we have extension stored in the starting.
    String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);

    InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));

    Bitmap bitmap = BitmapFactory.decodeStream(stream);

    imageView.setImageBitmap(bitmap);
}

【讨论】:

  • BitmapFactory.decodeStream(new BufferedInputStream(stream)););
  • BitmapFactory.decodeStream(new BufferedInputStream(stream));); decodeStream 其错误
  • 已修改。检查一下。
  • here 所述,每次使用后尝试刷新输入流。
  • 我知道这有点老了,但是您的 decodeBase64AndSetImage 函数没有返回 String。我只是将标题更改为 void.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多