gpt4 book ai didi

java - 如何在现有图像文件的顶部添加 20 像素的白色?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:13 24 4
gpt4 key购买 nike

我有一张 w 尺寸为 h 的图像。在 Java 中,我需要创建一个大小为 w 乘以 h+20 的图像,其中顶部 w 乘以 20 像素为白色,其余图像与原图相同。

本质上,我想知道如何将 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...
}

最佳答案

建议:

  1. 使用GraphicsConfiguration.createCompatibleImage(int width, int height)创建宽度相同但高度为 +20 的 BufferedImage
  2. 使用BufferedImage.createGraphics()获取此图像的 Graphics2D 对象。
  3. 使用Graphics.setColor(Color c)Graphics.fillRect(int x, int y, int width, int height)画白顶
  4. 使用Graphics.drawImage(Image img, int x, int y, ImageObserver observer)将原始图像绘制到新图像的指定坐标。
  5. 要保存新图像,请阅读 Writing/Saving an Image教程。

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);
}
}

enter image description here

关于java - 如何在现有图像文件的顶部添加 20 像素的白色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7028780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com