0

Can I get pixel value of image and crop its black part. For instance, I have the this image:

Image.

And I want something like this

image

without the black part.

Any possible solution on how to do this? Any libraries/code?

I am using Objective C.

I have seen this solution to the similar question but I don't understand it in detail. Please kindly provide steps in detail. Thanks.

Community
  • 1
  • 1

1 Answers1

1

Probably the fastest way of doing this is iterating through the image and find the border pixels which are not black. Then redraw the image to a new context clipping the rect received by border pixels.

By border pixels I mean the left-most, top-most, bottom-most and right-most. You can find a way to get the raw RGBA buffer from the UIImage through which you may then iterate through width and height and set the border values when appropriate. That means for instance to get leftMostPixel you would first set it to some large value (or to the image width) and then in the iteration if the pixel is not black and if leftMostPixel > x then leftMostPixel = x.

Now that you have the 4 bounding values you can create a frame from it. To redraw just the target rectangle you may use various tools with contexts but probably the easiest is creating the view with size of bounding rect and put an image view with the size of the original image on it and create a screenshot of the view. The image view origin must be minus the origin of the bounded rect though (we put it offscreen a bit).

You may encounter some issues with the orientation of the image though. If the image will have some orientation other then up the raw data will not respect that. So you need to take that into account when creating the bounded rect... Or redraw the image first to make it oriented correctly... Or you can even create a sub buffer with RGBA data and create the CGImage from those data and applying the same orientation to the output UIImage as with input.

So after getting the bounds there are quite a few procedures. Some are slower, some take more memory, some are simply hard to code and have edge cases.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • Thank you for explaining the answer Matic. I would really appreciate it if you could let me know of the steps/functions which can be used (or some sample project), for instance how to iterate through image? i.e how to get its pixel values? Then how to check where its pixels are black etc.. Some snippet of code would be of huge help – Iman Mustafa Mar 15 '16 at 10:29
  • http://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core-graphics should show you how to get the RGBA data; the for loop should in your case be per width and per height and not count. A black pixel is if its RGB components are zero so rawData[index] == 0, rawData[index+1] == 0... – Matic Oblak Mar 15 '16 at 11:24