0

I am trying to crop image inside bounding box from camera preview and display in a activity. I have a surfaceview and a square imageview on top of it. I have to capture image that appears only inside imageview. Following is my cropping code, No idea as to what is wrong here,Please help

                int width  = rotatedBitmap.getWidth();
                int height = rotatedBitmap.getHeight();
                int newWidth = (height > width) ? width : height;
                int newHeight = (height > width)? height - ( height - width) : height;
                int x = (width - height) / 2;
                x = (x < 0)? 0: x;
                int y = (height - width) / 2;
                y = (y < 0)? 0: y;
                Bitmap cropImg = Bitmap.createBitmap(rotatedBitmap, x, y,newWidth, newHeight);

what's wrong with my code?

Idea
  • 1
  • 2
  • Have you checked the captured bitmap (before cropping)? Is it fine? – Sahil Bajaj Feb 28 '16 at 18:20
  • @Sahil yes it is fine. I get the complete image of preview. but I need to capture image that is only inside the square view – Idea Feb 28 '16 at 18:41
  • The code looks fine. Could you add breakpoints or get logs to see what are width/height values you're getting? And what's the output bitmap that you're getting? same as original bitmap? – Sahil Bajaj Feb 28 '16 at 18:53
  • @Sahil, yes I did and I got height=2560 and width=1920 – Idea Feb 28 '16 at 18:56
  • What is the result? Is the app crashing? A bitmap of this size is going to be around 20MB and then another bitmap, i.e. the cropped bitmap is going to be another 16MB. I hope you're not getting an OOM exception. – Sahil Bajaj Feb 28 '16 at 18:59
  • @Sahil To be specific, I need to get a 300*300 dp square image from centre of surfaceview. But when the image is cropped, it is more than required size – Idea Feb 28 '16 at 19:00
  • No I am not getting any exception, the cropped image gets saved to sd card, but it is slightly bigger in size than 300*300 dp square image – Idea Feb 28 '16 at 19:02
  • Oh.. okay.. in that case... int finalWidth, finalHeight; finalWidth = finalHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics()); Now instead of newWidth and newHeight, use finalWidth and finalHeight. You will need to calculate x and y accordingly. – Sahil Bajaj Feb 28 '16 at 19:02
  • oh! alright. Will try now and let you know.. give me 2 min. I am sorry,i am not very clear with calculating x and y. Could you please let me know – Idea Feb 28 '16 at 19:08
  • Shouldn't x and y be calculated from centre of surfaceview ??, as of now, it is taking 300*300 dp square photofrom top left. I should take x and y from centre and it would fix. – Idea Feb 28 '16 at 19:11
  • @Sahil, Thank you so much, its working, it cropped 300*300 from top, i just took x and y cordinates from centre and its working. Thanks a lot – Idea Feb 28 '16 at 19:28

0 Answers0