How do I crop an image in Java?

前端 未结 7 1306
逝去的感伤
逝去的感伤 2020-11-29 00:22

I want to crop an image manually using the mouse.
Suppose the image has some text, and I want to select some text from an image, then for that purpose I want to crop th

相关标签:
7条回答
  • 2020-11-29 00:56

    There are two potentially major problem with the leading answer to this question. First, as per the docs:

    public BufferedImage getSubimage(int x, int y, int w, int h)

    Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

    Essentially, what this means is that result from getSubimage acts as a pointer which points at a subsection of the original image.

    Why is this important? Well, if you are planning to edit the subimage for any reason, the edits will also happen to the original image. For example, I ran into this problem when I was using the smaller image in a separate window to zoom in on the original image. (kind of like a magnifying glass). I made it possible to invert the colors to see certain details more easily, but the area that was "zoomed" also got inverted in the original image! So there was a small section of the original image that had inverted colors while the rest of it remained normal. In many cases, this won't matter, but if you want to edit the image, or if you just want a copy of the cropped section, you might want to consider a method.

    Which brings us to the second problem. Fortunately, it is not as big a problem as the first. getSubImage shares the same data array as the original image. That means that the entire original image is still stored in memory. Assuming that by "crop" the image you actually want a smaller image, you will need to redraw it as a new image rather than just get the subimage.

    Try this:

    BufferedImage img = image.getSubimage(startX, startY, endX, endY); //fill in the corners of the desired crop location here
    BufferedImage copyOfImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = copyOfImage.createGraphics();
    g.drawImage(img, 0, 0, null);
    return copyOfImage; //or use it however you want
    

    This technique will give you the cropped image you are looking for by itself, without the link back to the original image. This will preserve the integrity of the original image as well as save you the memory overhead of storing the larger image. (If you do dump the original image later)

    0 讨论(0)
提交回复
热议问题