I'm trying do the following code:
private void crop(HttpServletRequest request, HttpServletResponse response){ int x = 100; int y = 100; int w = 3264; int h = 2448; String path = "D:images\\upload_final\\030311175258.jpg"; BufferedImage image = ImageIO.read(new File(path)); BufferedImage out = image.getSubimage(x, y, w, h); ImageIO.write(out, "jpg", new File(path)); }
But keeps giving me the same error:
java.awt.image.RasterFormatException: (x + width) is outside of Raster sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1230) java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1156)
Where is my mistake ?
To “crop” an image is to remove or adjust the outside edges of an image (typically a photo) to improve framing or composition, draw a viewer's eye to the image subject, or change the size or aspect ratio. In other words, image cropping is the act of improving a photo or image by removing the unnecessary parts.
A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).
You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We'll use the BufferedImage class that extends the basic Image class. It stores images as an array of pixels.
My initial guess is that your (x + w) > image.getWidth()
.
If you print out image.getWidth(), is it 3264? :O
What you're currently doing is this:
<-- 3264 ------> +--------------+ | orig | +-- Causing the problem | | V | +--------------+ |100| overlap | | | | | | | | | | +---|----------+ | | | | out | +--------------+
If you're trying to trim off the top corner of orig, and just get "overlap" then you need to do
BufferedImage out = image.getSubimage(x, y, w-x, h-y);
If you're trying to do this:
+------------------+ | | | +-----------+ | | | | | | | | | | | | | | | | | | +-----------+ | | | +------------------+
Then you need to do this:
BufferedImage out = image.getSubimage(x, y, w-2*x, h-2*y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With