[英]How to resize and rotate an image
我想旋轉圖像,並在下一個級別中調整大小,請幫助我。 我創建了一個從JPanel擴展的類,並重寫了paintComponent()方法來繪制圖像。
public class NewJPanel extends javax.swing.JPanel {
/** Creates new form NewJPanel */
public NewJPanel() {
initComponents();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 20, 20, this);
}
這是我使用的一些代碼。 您可以修改它以滿足您的需求。
調整圖片大小:
/**
* Resizes the image
* @param filePath File path to the image to resize
* @param w Width of the image
* @param h Height of the image
* @return A resized image
*/
public ImageIcon resizeImage(String filePath, int w, int h) {
String data = filePath;
BufferedImage bsrc, bdest;
ImageIcon theIcon;
//scale the image
try
{
if(dataSource == DataTypeEnum.file)
{
bsrc = ImageIO.read(new File(data));
}
else
{
bsrc = ImageIO.read(new URL(filePath));
}
bdest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance((double) w / bsrc.getWidth(),
(double) h / bsrc.getHeight());
g.drawRenderedImage(bsrc, at);
//add the scaled image
theIcon = new ImageIcon(bdest);
return theIcon;
}
catch (Exception e)
{
Window.getLogger().warning("This image can not be resized. Please check the path and type of file.");
//restore the old background
return null;
}
}
旋轉圖像:
注意:角度以弧度為單位
public static BufferedImage rotate(BufferedImage image, double angle) {
double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
int w = image.getWidth(), h = image.getHeight();
int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww-w)/2, (newh-h)/2);
g.rotate(angle, w/2, h/2);
g.drawRenderedImage(image, null);
g.dispose();
return result;
}
沒有給出完整的解決方案
Graphics2D具有旋轉和縮放功能。
使用BufferedImage類
BufferedImage newImg =新的BufferedImage(newWidth,newHeight,imageType); newImg.createGraphics()。drawImage(oldImg,0,0,newWidth,newHeight,0,0,oldWidth,oldHeight,null);
然后只需使用newImg而不是舊圖像重新繪制,就可以正常工作,目前我不在編譯器進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.