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

纵饮孤独 提交于 2021-02-04 05:00:11

问题


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


回答1:


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.




回答2:


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()
}


来源:https://stackoverflow.com/questions/23130183/how-to-crop-the-image-using-four-x-y-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!