Thursday 22 August 2013

Crop Image

Intent for getting image from captured image

 Intent intent      = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                       "MyImage_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                    try {
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, CAMERA_RESULT);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }


Intent for getting image from sd card image

try {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), RESULT_LOAD_IMAGE);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }



then onActivityResult code

private static final int RESULT_LOAD_IMAGE = 101;
    private static final int CAMERA_RESULT = 102;
    private static final int CROP_FROM_CAMERA = 103;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case CAMERA_RESULT:
            try{
                doCrop();
            }catch(Exception e){
                e.printStackTrace();
            }
            break;

        case RESULT_LOAD_IMAGE:
            try{
                mImageCaptureUri = data.getData();
                doCrop();
            }catch(Exception e){
                e.printStackTrace();
            }
            break;          

        case CROP_FROM_CAMERA:    
          
            try{
                Bundle extras = data.getExtras();

                if (extras != null) {              
                     photo = extras.getParcelable("data");

                  
                    imguser.setImageBitmap(photo);
                    imguser.setBackgroundColor(getResources().getColor(R.color.transparent));
                }

                File f = new File(mImageCaptureUri.getPath());  
                Log.i(tag, "Get Image uri file........"+f);
                selectedImagePath = f.getAbsolutePath();
                Log.i(tag, "Get Absolute image path........"+selectedImagePath);
                if (f.exists()) f.delete();
              
                boolean success = false;
                if(photo != null){
                    Log.i(tag, "Bitmap.........."+photo);
                    try {
                        byte[] bitmapdata;
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.JPEG, 90, stream);
                        bitmapdata = stream.toByteArray();

                        if (bitmapdata != null) {
                            MyWrite(bitmapdata);
                            success = true;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        success = false;
                    }
                }
                if (success) {
                     Log.i(tag, "Image Saved Successfully");
                    } else {
                        Log.i(tag, "Error during image saving");
                    }  
            }catch(Exception e){
                e.printStackTrace();
            }
            break;
        }
    }  


Crop function

private Uri mImageCaptureUri;
Bitmap photo;
ImageView imguser;
String selectedImagePath
 

     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, "Can not find image crop app", Toast.LENGTH_SHORT).show();
              
                return;
            } else {
                intent.setData(mImageCaptureUri);
              
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);
                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("Choose Crop App");
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        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();
                }
            }
        }


    public void MyWrite(byte[] buffer) {
        System.gc();
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File(sdCard.getAbsolutePath() + "/MyImage");
        directory.mkdirs();
        // Now create the file in the above directory and write the contents
        // into it
        System.out.println("Image path=" + selectedImagePath);
        File file;
        file = new File(directory, currentDateandTime + ".jpg");

        // File file = new File(directory, "sample.jpg");
        selectedImagePath = file.getAbsolutePath();
        System.out.println("Path=" + selectedImagePath);

        try {
            if (!file.exists())
                file.createNewFile();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedOutputStream osw = new BufferedOutputStream(fOut);
        try {
            // osw.write(path);
            osw.write(buffer);
            // osw.write(buffer, offset, length);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

No comments:

Post a Comment

Comments

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...