我在Android设备中使用图像裁剪应用从相机或相册
裁剪图像图像将转换为字符串并将发送到服务器 所以在服务器上,图片大小 160X160 ,设备三星GALAXY Tab2 10.1
使用过的代码有什么问题?
调整代码大小以显示Thumb返回 120X120 图像和不向服务器发送Thumb
private String setBitmapToString(Bitmap bmp) {
String base64String = null;
if (bmp == null) {
bmp = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.app_icon);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imgBytes = baos.toByteArray();
base64String = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
ContentValues initialValues = new ContentValues();
initialValues.put("picture", base64String);
// save your base64String to DB
return base64String;
}
我使用以下方法拍摄照片或从设备中取出并最终裁剪:
//==================== Take Picture
ArrayList<String> images = new ArrayList<String>();
private Bitmap photo;
private Uri mImageCaptureUri;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
private void takePicture(){
final String[] items = new String[]{App.context.getString(R.string.SELECT_FROM_CAMERA), App.context.getString(R.string.SELECT_FROM_GALLERY)};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("انتخاب تصویر");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) { //pick from camera
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, App.context.getString(R.string.Complete_action_using)), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
rlImage1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelect = 1;
dialog.show();
}
});
rlImage2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelect = 2;
dialog.show();
}
});
rlImage3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelect = 3;
dialog.show();
}
});
rlImage4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelect = 4;
dialog.show();
}
});
txtSelectLogoNj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelect = 5;
dialog.show();
}
});
}
private int lastSelect = 4;
String image1 = "", image2 = "", image3 = "", image4 = "", image5 = "";
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
int w = (int) (UIHelpers.width * 0.15);
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) {
//f.delete();
}
Log.d("TakePicture", "File Path : " + f.getAbsolutePath() + " , Size : " + w);
switch (lastSelect){
case 5:
txtSelectLogoNj.setVisibility(View.GONE);
rlLogoNj.setVisibility(View.VISIBLE);
image5 = ""+setBitmapToString(photo);
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE5", image5);
App.editor.commit();
imgLogoNj.setImageBitmap(Bitmap.createScaledBitmap(photo, w, w, false));
break;
case 4:
image4 = ""+setBitmapToString(photo);
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE4", image4);
App.editor.commit();
imgImage4.setImageBitmap(Bitmap.createScaledBitmap(photo, w, w, false));
txtImage4.setVisibility(View.VISIBLE);
break;
case 3:
image3 = ""+setBitmapToString(photo);
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE3", image3);
App.editor.commit();
imgImage3.setImageBitmap(Bitmap.createScaledBitmap(photo, w, w, false));
txtImage3.setVisibility(View.VISIBLE);
break;
case 2:
image2 = ""+setBitmapToString(photo);
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE2", image2);
App.editor.commit();
imgImage2.setImageBitmap(Bitmap.createScaledBitmap(photo, w, w, false));
txtImage2.setVisibility(View.VISIBLE);
break;
case 1:
image1 = ""+setBitmapToString(photo);
App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
App.editor = App.sharedpreferences.edit();
App.editor.putString("IMAGE1", image1);
App.editor.commit();
imgImage1.setImageBitmap(Bitmap.createScaledBitmap(photo, w, w, false));
txtImage1.setVisibility(View.VISIBLE);
break;
}
}
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, getApplicationContext().getString(R.string.crop_unavailable), Toast.LENGTH_SHORT).show();
// return
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", UIHelpers.width);
intent.putExtra("outputY", UIHelpers.width);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res: list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getApplicationContext().getString(R.string.select_crop_app));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
//==================== Take Picture
以及 CropOption 和 CropOptionAdapter :
CropOptionAdapter:
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
CropOption:
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
被修改 我正在使用画廊来裁剪,我正在使用&#34; Bitmap photo&#34;所以它返回小图像,现在使用
文件f =新文件(mImageCaptureUri.getPath());
f.getAbsolutePath()
但在将图像发送到服务器之前,它会显示 OutOfMemory 错误
那个新问题
答案 0 :(得分:1)
内存不足问题可以通过将图库图像中的裁剪/图像固定为固定大小来解决。在onActivityResult中包括
//Temp file to save cropped image
private String mImagePath;
private Uri mSaveUri = null;
private Uri mImageUri = null;
//File for capturing camera images
private File mFileTemp;
if (resultCode == RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(result.getData()); // Got the bitmap .. Copy it to the temp file for cropping
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
mImagePath = mFileTemp.getPath();
mSaveUri = Utils.getImageUri(mImagePath);
mImageUri = Utils.getImageUri(mImagePath);
init();
} catch (Exception e) {
errored();
}
private static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
public class Utils {
public static Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
}
如果您想使用自定义库,我已创建一个并在GitHub
中共享