java bitmap base64_Android Bitmap到Base64字符串

本文详细介绍了如何使用Java处理位图,包括如何缩放图像以适应特定尺寸,以及如何将缩放后的位图转换为Base64字符串。提供了具体的代码示例,包括`getScaledBitmap`方法用于图像缩放,以及`getBase64String`方法用于Base64编码。这些步骤对于在Web应用中处理图像和存储图像数据非常有用。
摘要由CSDN通过智能技术生成

试试这个,首先将图像缩放到所需的宽度和高度,只需将原始位图,所需宽度和所需高度传递给以下方法,然后获得缩放位图:

例如:Bitmap scaledBitmap = getScaledBitmap(originalBitmap,250,350);

private Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)

{

int bWidth = b.getWidth();

int bHeight = b.getHeight();

int nWidth = bWidth;

int nHeight = bHeight;

if(nWidth > reqWidth)

{

int ratio = bWidth / reqWidth;

if(ratio > 0)

{

nWidth = reqWidth;

nHeight = bHeight / ratio;

}

}

if(nHeight > reqHeight)

{

int ratio = bHeight / reqHeight;

if(ratio > 0)

{

nHeight = reqHeight;

nWidth = bWidth / ratio;

}

}

return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);

}

现在只需将缩放的位图传递给以下方法并获取base64字符串:

例如:String base64String = getBase64String(scaledBitmap);

private String getBase64String(Bitmap bitmap)

{

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] imageBytes = baos.toByteArray();

String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);

return base64String;

}

要将base64字符串解码回位图图像:

byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);

Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值