有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在不压缩图像的情况下将图像转换为Base64字符串?

每次我更新同一张图片时,图像压缩方法会降低图像质量

 public String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    base64Image = Base64.encodeToString(b, Base64.DEFAULT);
    return base64Image;
}

我不想一次又一次地压缩图像。请提出一些建议


共 (1) 个答案

  1. # 1 楼答案

    首先,使用PNG压缩不会丢失图像质量

    如果仍要在不压缩的情况下获取字节,可以尝试以下操作:

    ByteBuffer buffer = ByteBuffer.allocate(bitmap.getRowBytes() * bitmap.getHeight());
    bitmap.copyPixelsToBuffer(buffer);
    byte[] data = buffer.array();
    

    要从字节数组获取Bitmap,请执行以下操作:

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(data));
    return bitmap;