-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageResizer.java
63 lines (53 loc) · 1.95 KB
/
ImageResizer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//created by Aryeh Bloom and Jack Seigerman
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
// Custom panel for displaying an image
public class ImageResizer extends JPanel
{
// The image to be displayed (instance-specific)
private BufferedImage image;
// Override the paintComponent method to draw the image
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int panelWidth = getWidth();
int panelHeight = getHeight();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double panelAspect = (double) panelWidth / panelHeight;
double imageAspect = (double) imageWidth / imageHeight;
int drawWidth, drawHeight;
if (panelAspect > imageAspect)
{
drawHeight = panelHeight;
drawWidth = (int) (panelHeight * imageAspect);
}
else
{
drawWidth = panelWidth;
drawHeight = (int) (panelWidth / imageAspect);
}
int x = (panelWidth - drawWidth) / 2;
int y = (panelHeight - drawHeight) / 2;
g2d.drawImage(image, x, y, drawWidth, drawHeight, this);
}
}
// Method to set the image and repaint the panel
public void setImage(BufferedImage image)
{
this.image = image;
repaint();
}
// Getter method for the image (non-static now)
public BufferedImage getImage(){
return image;
}
}