Android中base64字符串编码和解码位图对象 [英] Encode and decode bitmap object in base64 string in Android

查看:40
本文介绍了Android中base64字符串编码和解码位图对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对字符串 base64 中的 Bitmap 对象进行编码和解码.我用的是Android API10,

I want to encode and decode Bitmap object in string base64. I use the Android API10,

我尝试使用这种形式的方法来编码 Bitmap,但没有成功.

I have tried, with no success, to use a method in this form to encode a Bitmap.

public static String encodeTobase64(Bitmap image) {
    Bitmap immagex=image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);

    Log.e("LOOK", imageEncoded);
    return imageEncoded;
}

推荐答案

public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)
{
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    image.compress(compressFormat, quality, byteArrayOS);
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}

public static Bitmap decodeBase64(String input)
{
    byte[] decodedBytes = Base64.decode(input, 0);
    return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}

示例用法:

String myBase64Image = encodeToBase64(myBitmap, Bitmap.CompressFormat.JPEG, 100);
Bitmap myBitmapAgain = decodeBase64(myBase64Image);

这篇关于Android中base64字符串编码和解码位图对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆