Ankit
Ankit

Reputation: 4644

Create a cropped bitmap from an original bitmap

In my android application I have a Bitmap and I want to create another bitmap which is cropped out of this bitmap. In other words I want to get a particular portion from the original Bitmap.

I am using Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height) but the image which I get in return appears to be zoomed in.

What could be the reason, and how can I correct this? Please help

Upvotes: 2

Views: 3434

Answers (4)

shakirullah orakzai
shakirullah orakzai

Reputation: 356

  Rect re=new Rect(350, 150, 350, 150);



    public void takePicture(final String fileName) {
    Log.i(TAG, "Tacking picture");
    PictureCallback callback = new PictureCallback() {

        private String mPictureFileName = fileName;

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Log.i(TAG, "Saving a bitmap to file");
            Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
           Bitmap finalBitmap = Bitmap.createBitmap(picture, 850, 500, 960, 720);

            try {


                FileOutputStream out = new FileOutputStream(mPictureFileName);
                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                finalBitmap.recycle();
                mCamera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    mCamera.takePicture(null, null, callback);

}

Upvotes: 0

Sanandrea
Sanandrea

Reputation: 2194

My advice:

r = this.getContext().getResources();
Drawable copyFrom= r.getDrawable(R.drawable.OriginalPNG);
Bitmap b1 = Bitmap.createBitmap(IMAGES_WIDTH, IMAGES_HEIGHT,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b1);


copyFrom.setBounds(0, 0, IMAGES_WIDTH, IMAGES_HEIGHT);
copyFrom.draw(canvas);

Bitmap copyTo;  

copyTo = Bitmap.createBitmap(copyFrom, x, y, W, H);

where IMAGES_WIDTH and IMAGES_HEIGHT are the dimensions of the original PNG and W,H are the dimensions of the area you want to copy. x and y specify the point on the original PNG from where to begin to copy. Putting x,y both to zero means starting from the upper-left corner.

Upvotes: 1

nmw
nmw

Reputation: 6764

Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height) is definitely the correct method. I suspect you're just using the parameters incorrectly.

E.g. To get the centre 50x50 pixels of a 100x100 bitmap named img, you'd use:

Bitmap.createBitmap(img, 25, 25, 50, 50);

Upvotes: 2

Vipul
Vipul

Reputation: 28093

Here you go

https://github.com/lorensiuswlt/AndroidImageCrop

Upvotes: 0

Related Questions