问题
How to optimize this peace of code?
It takes about a minute on saveImage
method.
class ObrolSimpleHost extends SimpleCameraHost {
private final String[] SCAN_TYPES = {"image/webp"};
private Context context = null;
public ObrolSimpleHost(Context _ctxt) {
super(_ctxt);
this.context = getActivity();
}
@Override public void saveImage(PictureTransaction xact, Bitmap bitmap) {
File photo = getPhotoPath();
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
bitmap.compress(Bitmap.CompressFormat.WEBP, 70, fos);
fos.flush();
fos.getFD().sync();
if (scanSavedImage()) {
MediaScannerConnection.scanFile(context, new String[]{photo.getPath()}, SCAN_TYPES, null);
}
} catch (java.io.IOException e) {
handleException(e);
}
}
@Override public void saveImage(PictureTransaction xact, byte[] image) {
// do nothing
}
}
I am calling ObrolSimpleHost
from CameraFragment:
PictureTransaction xact = new PictureTransaction(getHost());
xact.needBitmap(true);
takePicture(xact);
回答1:
Here is my own answer.
Fixed issues which CommonsWare
mentioned and resize bitmap
before compression by createScaledBitmap
:
class ObrolSimpleHost extends SimpleCameraHost {
private final String[] SCAN_TYPES = {"image/" + imputType};
private Context context = null;
public ObrolSimpleHost(Context _ctxt) {
super(_ctxt);
this.context = getActivity();
}
@Override public void saveImage(PictureTransaction xact, Bitmap bitmap) {
File photo = getPhotoPath();
String path = photo.getPath().replace("jpg", imputType);
if (photo.exists()) {
photo.delete();
}
/**
* Resizing bitmap, so save some ms in compression
* http://stackoverflow.com/questions/17839388/creating-a-scaled-bitmap-with-createscaledbitmap-in-android
*/
final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = bitmap.getWidth();
int inHeight = bitmap.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
try {
FileOutputStream fos = new FileOutputStream(path);
if (imputType.equals("jpeg")) {
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
} else {
resizedBitmap.compress(Bitmap.CompressFormat.WEBP, 70, fos);
}
fos.flush();
fos.getFD().sync();
if (scanSavedImage()) {
MediaScannerConnection.scanFile(context, new String[]{photo.getPath()}, SCAN_TYPES, null);
}
} catch (java.io.IOException e) {
handleException(e);
}
EventBus.getDefault().postSticky(new Events.PreparingBitmapEvent(path));
getActivity().finish();
}
@Override public void saveImage(PictureTransaction xact, byte[] image) {
// do nothing
}
}
Instead of standard bitmap
use other library which build with JNI
In my case I am going to try Roid-WebP
来源:https://stackoverflow.com/questions/25142160/cwac-camera-why-my-simplecamerahost-saveimage-is-so-slow-am-i-doing-something