android 摄像头图像数据YUV转Bitmap, 再转Base64

废话不说直接上代码,亲测可用

1.YUV数组转Bitmap

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;

/**
*http://tech.srij.it/2013/02/get-bitmap-image-from-yuv-in-android.html
*/
public class Utils {
       public static Bitmap getBitmapImageFromYUV(byte[] data, int width, int height) {
              YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              yuvimage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
              byte[] jdata = baos.toByteArray();
              BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
              bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
              Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, bitmapFatoryOptions);
              return bmp;
       }

}

2.Bitmap转Base64

    private String bitmap2base64(Bitmap bitmap){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT).trim().replaceAll("\n", "").replaceAll("\r", "");
    }

另外补充一下, 转换玩的Base64字符串直接在控制台打印的话可能打印不全,控制台一次性貌似只能输出4k多个字符, 如果想拿字符串转回图片看效果的话,可以输出成txt文件。

你可能感兴趣的:(程序员,成长之路,Android,android,YUV,bitmap,base64)