Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a method which will work:</p> <pre><code>import java.awt.image.BufferedImage; import java.awt.Rectangle; import java.awt.Color; import java.awt.Graphics; public BufferedImage crop(BufferedImage src, Rectangle rect) { BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_ARGB_PRE); Graphics g = dest.getGraphics(); g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null); g.dispose(); return dest; } </code></pre> <p>Of course you have to make your own JComponent:</p> <pre><code>import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.awt.Rectangle; import java.awt.Graphics; import javax.swing.JComponent; public class JImageCropComponent extends JComponent implements MouseListener, MouseMotionListener { private BufferedImage img; private int x1, y1, x2, y2; public JImageCropComponent(BufferedImage img) { this.img = img; this.addMouseListener(this); this.addMouseMotionListener(this); } public void setImage(BufferedImage img) { this.img = img; } public BufferedImage getImage() { return this; } @Override public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, this); if (cropping) { // Paint the area we are going to crop. g.setColor(Color.RED); g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)); } } @Override public void mousePressed(MouseEvent evt) { this.x1 = evt.getX(); this.y1 = evt.getY(); } @Override public void mouseReleased(MouseEvent evt) { this.cropping = false; // Now we crop the image; // This is the method a wrote in the other snipped BufferedImage cropped = crop(new Rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)); // Now you have the cropped image; // You have to choose what you want to do with it this.img = cropped; } @Override public void mouseDragged(MouseEvent evt) { cropping = true; this.x2 = evt.getX(); this.y2 = evt.getY(); } //TODO: Implement the other unused methods from Mouse(Motion)Listener } </code></pre> <p>I didn't test it. Maybe there are some mistakes (I'm not sure about all the imports).<br></p> <p>You can put the <code>crop(img, rect)</code> method in this class. Hope this helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload