62,621
社区成员
发帖
与我相关
我的任务
分享
package testGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class TestImage extends JFrame {
private static final long serialVersionUID = 1L;
private static final String filename = "C:/1.jpg";
private volatile BufferedImage image = null;
public TestImage() {
init();
}
private void init() {
this.getContentPane().setLayout(new BorderLayout());
this.setSize(new Dimension(800, 600));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addComponentListener(new MyAdapter(this));
this.setVisible(true);
}
public BufferedImage getImage(boolean reload) {
if (image == null || reload) {
try {
image = ImageIO.read(new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
return image;
}
public void resize(int height, int width, boolean bb) {
try {
double ratio = 0.0;
File f = new File(filename);
BufferedImage bi = getImage(false);
Image itemp = getImage(false).getScaledInstance(width, height,
BufferedImage.SCALE_SMOOTH);
if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
if (bi.getHeight() > bi.getWidth()) {
ratio = (new Integer(height)).doubleValue()
/ bi.getHeight();
} else {
ratio = (new Integer(width)).doubleValue() / bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
}
if (bb) {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
if (width == itemp.getWidth(null))
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
else
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "jpg", f);
TestImage.this.getGraphics().drawImage(getImage(true), this.getX(),
this.getY(), TestImage.this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(getImage(false), this.getX(), this.getY(), this);
}
/**
* @param args
*/
public static void main(String[] args) {
new TestImage();
}
}
class MyAdapter extends ComponentAdapter {
TestImage adaptee;
MyAdapter(TestImage adaptee) {
this.adaptee = adaptee;
}
public void componentResized(ComponentEvent e) {
adaptee.resize(adaptee.getHeight(), adaptee.getWidth(), true);
}
}