在Android中,您可以使用以下步骤来先压缩图片,然后将其转换为Base64编码:

  1. 导入相关类:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
  1. 压缩图片:
public Bitmap compressImage(String imagePath) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, options);

    // 计算缩放比例
    int scale = Math.max(options.outWidth / 800, options.outHeight / 800);

    options.inJustDecodeBounds = false;
    options.inSampleSize = scale;

    return BitmapFactory.decodeFile(imagePath, options);
}

这个方法将根据图片的宽高比例计算出一个适当的缩放比例,并返回压缩后的Bitmap对象。

  1. 将Bitmap转为Base64编码:
public String bitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

这个方法将压缩后的Bitmap对象转换为字节数组,然后使用Base64编码转换为字符串。

  1. 调用方法:
String imagePath = "your_image_path";
Bitmap compressedBitmap = compressImage(imagePath);
String base64String = bitmapToBase64(compressedBitmap);

请确保替换"your_image_path"为您实际的图片路径。

这样,您就可以先压缩图片,然后将其转换为Base64编码了

android中如何先压缩图片再转为BASE64

原文地址: https://www.cveoy.top/t/topic/h7yH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录