search
HomeJavajavaTutorialHow to implement an image cropping function in Java

Listing1: 引入的类

import java.awt.Graphics;  import java.awt.Rectangle;  import java.awt.Robot;  import java.awt.event.MouseEvent;  import java.awt.event.MouseListener;  import java.awt.event.MouseMotionListener;  import java.awt.image.BufferedImage;  import java.io.File;  import javax.imageio.ImageIO;  import javax.swing.JFrame;

说明:

  1. Graphics 类包含绘制矩形的方法

  2. 我们使用 Rectangle 类作为拖拉的矩形区域以作剪裁

  3. Robot 类用于捕获屏幕截图

  4. 使用鼠标侦听器来获取鼠标的拖拉时间

  5. Robot 类使用 BufferedImage 来做图像处理

  6. File 类用于打开图像文件

  7. ImageIO 类用于将图像写到 png 或者 jpg 图像文件中

  8. JFrame 用于显示界面

现在我们编写包含 main 方法的入口类

Listing2: 入口类

public class CropImage extends JFrame implements MouseListener, MouseMotionListener  {      int drag_status=0,c1,c2,c3,c4;  public static void main(String args[])  {      new CropImage().start();  }

说明:

  1. 编写了一个名为 CropImage 的类

  2. 该类扩展了 JFrame 以实现 frame 的所有功能

  3. 实现了不同的鼠标事件侦听器以便知道用户什么时候开始拖动鼠标指针

  4. drag_status 变量用于保存鼠标开始拖动时的坐标

  5. 我们定义了 main 方法去调用一个 start 方法,这个方法将在下面定义

接下来是 start 方法

Listing 2

public void start()  {      ImagePanel im=new ImagePanel("F:\\Wallpaper\\wallpapers\\1.jpg");      add(im);      setSize(400,400);      setVisible(true);      addMouseListener(this);      addMouseMotionListener( this );      setDefaultCloseOperation(EXIT_ON_CLOSE);  }

说明:

  1. 我们定义一个名为 ImagePanel 的类,使用要处理的图像作为参数

  2. 在 JFrame 中放置这个要显示图片的 ImagePanel,并开始侦听鼠标事件

下面我们定义用于处理鼠标事件的方法

Listing 3: 鼠标事件处理函数

@Override public void mouseClicked(MouseEvent arg0) {  }     @Override public void mouseEntered(MouseEvent arg0) {  }     @Override public void mouseExited(MouseEvent arg0) {  }     @Override public void mousePressed(MouseEvent arg0) {      repaint();      c1=arg0.getX();      c2=arg0.getY();  }     @Override public void mouseReleased(MouseEvent arg0) {      repaint();      if(drag_status==1)      {      c3=arg0.getX();      c4=arg0.getY();      try     {      draggedScreen();      }      catch(Exception e)      {          e.printStackTrace();      }      }  }     @Override public void mouseDragged(MouseEvent arg0) {      repaint();      drag_status=1;      c3=arg0.getX();      c4=arg0.getY();  }   @Override public void mouseMoved(MouseEvent arg0) {         }     public void paint(Graphics g)  {      super.paint(g);      int w = c1 - c3;      int h = c2 - c4;      w = w * -1;      h = h * -1;      if(w<p>说明:</p><ol class=" list-paddingleft-2">
<li><p>当鼠标按下时存储当前坐标到 c1 和 c2</p></li>
<li><p>当鼠标按下并开始拖动时将拖动状态变量 drag_status 设置为 true</p></li>
<li><p>到鼠标按键松开时表示图像剪裁区域已经选择完毕,调用 draggedscreen 方法</p></li>
<li><p>paint 方法用于拖动时候的矩形显示,通过当前坐标和初始记录的坐标来绘制矩形</p></li>
</ol><p>下面是 draggedscreen 方法的代码</p><p><strong>Listing 4: </strong>draggedScreen 方法</p><pre class="brush:php;toolbar:false">public void draggedScreen()throws Exception  {          int w = c1 - c3;          int h = c2 - c4;          w = w * -1;          h = h * -1;          Robot robot = new Robot();          BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,w,h));          File save_path=new File("screen1.jpg");          ImageIO.write(img, "JPG", save_path);      System.out.println("Cropped image saved successfully.");  }}

说明:

  1. 首先计算图像的高度和宽度

  2. 使用 Robot 类来对剪裁的区域进行截图并保持到另外一个文件 screen1.jpg

完整的代码

Listing 5: ImagePanel.java

import java.awt.Dimension;  import java.awt.Graphics;  import java.awt.Image;     import javax.swing.ImageIcon;  import javax.swing.JPanel;         class ImagePanel extends JPanel {               private Image img;               public ImagePanel(String img) {              this(new ImageIcon(img).getImage());            }               public ImagePanel(Image img) {              this.img = img;              Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));             // Dimension size = new Dimension(10,10);              setPreferredSize(size);              setMinimumSize(size);              setMaximumSize(size);              setSize(size);              setLayout(null);            }               public void paintComponent(Graphics g) {              g.drawImage(img, 0, 0, null);            }             }

Listing 6:CropImage.java

import java.awt.Graphics;  import java.awt.Rectangle;  import java.awt.Robot;  import java.awt.event.MouseEvent;  import java.awt.event.MouseListener;  import java.awt.event.MouseMotionListener;  import java.awt.image.BufferedImage;  import java.io.File;  import javax.imageio.ImageIO;  import javax.swing.JFrame;     public class CropImage extends JFrame implements MouseListener, MouseMotionListener  {      int drag_status=0,c1,c2,c3,c4;  public static void main(String args[])  {      new CropImage().start();  }  public void start()  {      ImagePanel im=new ImagePanel("F:\\Wallpaper\\wallpapers\\1.jpg");      add(im);      setSize(400,400);      setVisible(true);      addMouseListener(this);      addMouseMotionListener( this );      setDefaultCloseOperation(EXIT_ON_CLOSE);  }  public void draggedScreen()throws Exception  {          int w = c1 - c3;          int h = c2 - c4;          w = w * -1;          h = h * -1;          Robot robot = new Robot();          BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,w,h));          File save_path=new File("screen1.jpg");          ImageIO.write(img, "JPG", save_path);      System.out.println("Cropped image saved successfully.");  }  @Override public void mouseClicked(MouseEvent arg0) {      }     @Override public void mouseEntered(MouseEvent arg0) {      }     @Override public void mouseExited(MouseEvent arg0) {       }     @Override public void mousePressed(MouseEvent arg0) {      repaint();      c1=arg0.getX();      c2=arg0.getY();  }     @Override public void mouseReleased(MouseEvent arg0) {      repaint();      if(drag_status==1)      {      c3=arg0.getX();      c4=arg0.getY();      try     {      draggedScreen();      }      catch(Exception e)      {          e.printStackTrace();      }      }  }     @Override public void mouseDragged(MouseEvent arg0) {      repaint();      drag_status=1;      c3=arg0.getX();      c4=arg0.getY();  }     @Override public void mouseMoved(MouseEvent arg0) {         }     public void paint(Graphics g)  {      super.paint(g);      int w = c1 - c3;      int h = c2 - c4;      w = w * -1;      h = h * -1;      if(w

The above is the detailed content of How to implement an image cropping function in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

What are the key components of the Java Runtime Environment (JRE)?What are the key components of the Java Runtime Environment (JRE)?Apr 22, 2025 pm 06:33 PM

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

Explain how the JVM handles memory management, regardless of the underlying operating system.Explain how the JVM handles memory management, regardless of the underlying operating system.Apr 22, 2025 pm 05:45 PM

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor