Cod*_*Guy 6 java swing bufferedimage
我有一个大小的图像w
通过h
.在Java中,我需要创建一个图像,其大小w
由h+20
top w
by 20 pixels
为白色,图像的其余部分与原始图像相同.
基本上我想知道如何在现有缓冲图像的顶部添加20像素的白色.
所以它会是这样的:
public static void main (String[] args) {
BufferedImage originalImage = [the original image with a specific file path];
...code to create a new image 20 pixels higher...
...code to paint originalImage 20 pixels down on the new image
...code to save the new image...
}
Run Code Online (Sandbox Code Playgroud)
mre*_*mre 13
建议:
GraphicsConfiguration.createCompatibleImage(int width, int height)
创建BufferedImage
的宽度相同,但随着高度这是+20.BufferedImage.createGraphics()
获得Graphics2D
此图像的对象.Graphics.setColor(Color c)
和Graphics.fillRect(int x, int y, int width, int height)
绘制白色顶部Graphics.drawImage(Image img, int x, int y, ImageObserver observer)
将原始图像绘制到新图像的指定坐标.import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class ImageManipulationDemo {
private static BufferedImage ORIGINAL;
private static BufferedImage ALTERED;
private static final GraphicsConfiguration config =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
public static void main(String[] args) {
try {
loadImages();
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadImages() throws IOException {
ORIGINAL = ImageIO.read(
ImageManipulationDemo.class.getResource("../resources/whitefro1.jpg"));
ALTERED = config.createCompatibleImage(
ORIGINAL.getWidth(),
ORIGINAL.getHeight() + 20);
Graphics2D g2 = ALTERED.createGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, ALTERED.getWidth(), 20);
g2.drawImage(ORIGINAL, 0, 20, null);
g2.dispose();
// Save image
ImageIO.write(ALTERED, "PNG", new File("alteredImage.png"));
}
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Image Manipulation Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.BLUE.darker());
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JLabel(new ImageIcon(ORIGINAL)));
frame.getContentPane().add(new JLabel(new ImageIcon(ALTERED)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2780 次 |
最近记录: |