Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop the image using four (x,y) coordinates

In my application ,I am going to crop the image using four (x,y) coordinates and also I need to show the cropped image in another activity screen. For example, In the below image, i want to crop the white layer itself. so any one provide the solution to accomplish this technique in my project.

Example image

like image 329
Manoj Avatar asked Apr 17 '14 10:04

Manoj


People also ask

How do I crop a picture to a specific dimension?

Select the Rectangular Marquee Tool from the palette, or hit M on your keyboard. In the toolbar at the top for this tool, you'll find a drop-down menu labeled 'Style. ' Choose either Fixed Ratio or Fixed Size, depending on whether you know the desired aspect ratio or exact dimensions for the final image.


2 Answers

I have already done such functionality in one of my apps. Kindly check the code below on how you can crop the captured image from camera.

val bytes = cropImage(capturedBitmap!!, viewBinding.viewFinder, viewBinding.containerOverly)

val croppedImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

private fun cropImage(bitmap: Bitmap, containerImage: View, containerOverlay: View): ByteArray {
    val heightOriginal = containerImage.height
    val widthOriginal = containerImage.width
    val heightFrame = containerOverlay.height
    val widthFrame = containerOverlay.width
    val leftFrame = containerOverlay.left
    val topFrame = containerOverlay.top
    val heightReal = bitmap.height
    val widthReal = bitmap.width
    val widthFinal = widthFrame * widthReal / widthOriginal
    val heightFinal = heightFrame * heightReal / heightOriginal
    val leftFinal = leftFrame * widthReal / widthOriginal
    val topFinal = topFrame * heightReal / heightOriginal
    val bitmapFinal = Bitmap.createBitmap(
        bitmap,
        leftFinal, topFinal, widthFinal, heightFinal
    )
    val stream = ByteArrayOutputStream()
    bitmapFinal.compress(
        Bitmap.CompressFormat.JPEG,
        100,
        stream
    ) //100 is the best quality possibe
    return stream.toByteArray()
}
like image 23
Hantash Nadeem Avatar answered Sep 20 '22 03:09

Hantash Nadeem


Using an instance of the Bitmap class, you can use the Bitmap.creatBitmap(); method passing the original image x y (for the top left corner) and then width and height.

see documentation here.

in your original example it would be:

Bitmap newBitmap=Bitmap.createBitmap(oldBitmap,10,20,70,80);

Edit

The Bitmap class also allows you to access an array of pixel int's representing color. if you know the shape you want to crop in terms of co-ordinates of each point. you could iterate through the array and set alpha to full on the ones that are outside your shape.

like image 67
Michael Kent Avatar answered Sep 20 '22 03:09

Michael Kent