如何在Android中将位图转换为PNG,然后转换为base64? [英] How to convert bitmap to PNG and then to base64 in Android?

查看:203
本文介绍了如何在Android中将位图转换为PNG,然后转换为base64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

顾名思义,我正在尝试让我的Android应用程序的用户从其设备中选择图片(完成),然后我希望将图片缩小(完成),将图片压缩/转换为png并将其作为base64字符串发送到API.

As the title implies, I'm trying to get the user of my Android app to select an image from his device (done), I then want to scale the image down (done), compress/convert the image to png and send it to an API as a base64 string.

所以我目前正像这样调整图像的大小:

So I currently resize the image like so:

options.inSampleSize = calculateInSampleSize(options, MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

然后我有了一个位图,我想将其转换为PNG,然后从那里转换为base64.我在此处找到了一些示例代码,可以转换为PNG并将其存储在设备上.

I then have a bitmap, which I want to convert to a PNG, and from there to a base64. I found some example code to convert to a PNG and store it on the device here.

try {
       FileOutputStream out = new FileOutputStream(filename);
       bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
       out.close();
} catch (Exception e) {
       e.printStackTrace();
}

问题是我不想保存图像.我只想将其作为PNG保留在内存中,然后将其进一步转换为base64字符串.

The problem is that I do not want to save the image. I just want to keep it in memory as a PNG and then convert it further to a base64 string.

有人知道我如何将图像转换为png并以这种方式存储在变量中,甚至更好地将其立即转换为base64吗?欢迎所有提示!

Does anybody know how I could convert the image to a png and store it in a variable that way, or even better, convert it to base64 immediately? All tips are welcome!

推荐答案

尝试将位图转换为png:

Try this to convert bitmap into png:

 bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

检查您可以直接将位图转换为Base64.用它来对Base64进行编码和解码.

You can directly convert bitmap to Base64. Use this for encoding and decoding from and to Base64.

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 Bitmap decodeBase64(String input) 
{
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
}

这篇关于如何在Android中将位图转换为PNG,然后转换为base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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