1、可以保存RBGA,或者yuv420
2、可以在同一个线程保存,或者抛到异步线程
同一个线程即不需要启动thread,直接调用saveImage
异步线程的话启动thread,用queueEvent把saveImage丢进队列执行
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Build;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
public class RGBAImageSaver extends Thread {
private static final String TAG = "RGBAImageSaver";
private static final String prefixName = "test_";
private static final String subfixName = ".jpg";
private File mDir = null;
private int mIndex = 0;
private boolean mStop = false;
private final Object mLock = new Object();
private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
public RGBAImageSaver(Context context, String dirName) {
mDir = new File(context.getFilesDir(), dirName);
if (mDir.exists()) {
mDir.delete();
}
mDir.mkdir();
}
public void queueEvent(Runnable event) {
synchronized (mEventQueue) {
mEventQueue.add(event);
}
synchronized (mLock) {
mLock.notify();
}
}
public void stopRunning() {
synchronized (mLock) {
mStop = true;
mLock.notify();
}
}
@Override
public void run() {
while(!mStop) {
Runnable event = null;
synchronized (mEventQueue) {
if(!mEventQueue.isEmpty()) {
event = mEventQueue.remove(0);
}
}
if(event != null) {
event.run();
}
synchronized (mLock) {
try {
if(!mStop && mEventQueue.isEmpty()) {
mLock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean saveImage(byte[] data, int width, int height, boolean isYuv420) {
if(data == null) {
return false;
}
File file = new File(mDir.getAbsolutePath(), prefixName + mIndex++ + subfixName);
if(isYuv420) {
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, width, height), 80, baos);
Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
try {
FileOutputStream outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 85, outStream);
outStream.write(baos.toByteArray());
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(data));
try {
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
bm.recycle();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}