How to convert image to string in Android?

只愿长相守 提交于 2020-01-13 06:59:07

问题


It's my MySql DB Its encoding:-

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;
}

This is decoding:-

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

Thank you.


回答1:


It could be done by

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);
}

And for Decode

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);
}


来源:https://stackoverflow.com/questions/41396194/how-to-convert-image-to-string-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!