图片的缩放

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class ImageSuoFang extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;
DrawResImg dri;
BorderLayout bl;

public ImageSuoFang() {
dri = new DrawResImg("D://1.png");
bl = new BorderLayout();
setMinimumSize(new Dimension(1000, 800));
setLayout(bl);
add(dri, bl.CENTER);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}

class DrawResImg extends JPanel implements MouseWheelListener{

/**
*
*/
private static final long serialVersionUID = 1L;
BufferedImage resBI;
BufferedImage resBI2;
int count = 0;

public DrawResImg(String path) {
try {
resBI = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
resBI2 = resBI;
addMouseWheelListener(this);
}

public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(resBI2, 200, 100, this);
}


public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getWheelRotation() < 0) {
count--;
}
if (e.getWheelRotation() > 0) {
count++;
}

resBI2 = resizePic(resBI, resBI.getWidth() + (10 * count), resBI.getHeight() + (10 * count));

repaint();
}

}

private static BufferedImage resizePic(BufferedImage source, int targetW,
int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
// 则将下面的if else语句注释即可
if (sx < sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
} else {
sy = sx;
targetH = (int) (sy * source.getHeight());
}
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
// smoother than exlax:
/*g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC); */
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
//g.dispose();
return target;
}


public static void main(String[] arg){
new ImageSuoFang();
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值