android裁剪图像太小

Posted

技术标签:

【中文标题】android裁剪图像太小【英文标题】:android croped image is too small 【发布时间】:2015-06-20 10:45:00 【问题描述】:

我在 android 设备中使用图像裁剪器应用从 相机图库

裁剪图像

图像将转换为字符串并将发送到服务器 以此类推服务器,图片尺寸为160X160,设备为Samsung 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

还有 CropOptionCropOptionAdapter

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;
    

裁剪选项:

public class CropOption 
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;

已编辑 我正在使用图库进行裁剪,我使用“位图照片”所以它返回小图像,现在使用

文件 f = new File(mImageCaptureUri.getPath());

f.getAbsolutePath()

但在将图像发送到服务器之前,它会显示 OutOfMemory 错误

这是新问题

【问题讨论】:

“我在 android 设备中使用默认裁剪应用程序” -- there is no default crop app in Android devices。有许多image cropping libraries 可用于 Android。请使用一个。 【参考方案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共享

【讨论】:

以上是关于android裁剪图像太小的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 上即时裁剪图像

无法在android中裁剪图像

Android中自定义图像裁剪的实现

Android - 从多点裁剪图像

裁剪缩放“Android”的图像

裁剪后的Android图像视图仅显示小图像