【发布时间】:2021-10-10 09:17:48
【问题描述】:
我创建了 4 个缓冲图像对象并用不同的颜色填充它们。然后创建一个更大的 bufferedimage 对象并将之前创建的所有四个 buff.image 绘制到其中以创建更大的图像。然后我将大图像保存到带有 gif 扩展名的文件中。虽然大小正确,但 gif 文件不包含颜色。为什么 ?我的错在哪里?
import java.awt.HeadlessException;
import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class MainFrame extends JFrame implements Runnable{
public MainFrame() throws HeadlessException {
ImagePanel ip=new ImagePanel(this);
add(ip,"Center");
}
public static void main(String[] args) {
MainFrame mf=new MainFrame();
mf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
mf.setSize(new Dimension(800,600));
mf.setLocationRelativeTo(null);
mf.setVisible(true);
}
}
class ImagePanel extends JPanel {
public ImagePanel(MainFrame jf) {
ImageJoiner imj=new ImageJoiner();
}
}
class ImageJoiner {
// this will joing four buffered images together to construct bigger image as buffered image and save it as gif file
public ImageJoiner() {
createImages();
}
public void createImages() {
imtl=new BufferedImage(PW, PH, BufferedImage.TYPE_INT_RGB);
imtr=new BufferedImage(PW, PH, BufferedImage.TYPE_INT_RGB);
imbl=new BufferedImage(PW, PH, BufferedImage.TYPE_INT_RGB);
imbr=new BufferedImage(PW, PH, BufferedImage.TYPE_INT_RGB);
bigW=PW*2;
bigH=PH*2;
bigmap=new BufferedImage(bigW, bigH, BufferedImage.TYPE_INT_RGB);
imtl.createGraphics().setColor(Color.blue);
imtl.createGraphics().fillRect(0,0, PW, PH);
imtr.getGraphics().setColor(Color.red);
imtr.getGraphics().fillRect(0, 0, PW, PH);
imbl.getGraphics().setColor(Color.green);
imbl.getGraphics().fillRect(0, 0, PW, PH);
imbr.getGraphics().setColor(Color.yellow);
imbr.getGraphics().fillRect(0, 0, PW, PH);
bigmap.getGraphics().drawImage(imtl, 0, 0,PW,PH,null);
bigmap.getGraphics().drawImage(imtr, PW, 0,PW,PH,null);
bigmap.getGraphics().drawImage(imbl, 0, PH, PW,PH,null);
bigmap.getGraphics().drawImage(imbr, PW, PH,PW,PH,null);
writeBufferedImageToFile(bigmap);
}
private void writeBufferedImageToFile(BufferedImage bim) {
File file = new File("images/out.gif");
try {
ImageIO.write(bim, "gif", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static final int PW =1000;
static final int PH =1000;
static int bigW,bigH;
BufferedImage imtl,imtr,imbl,imbr;
BufferedImage bigmap;
}
【问题讨论】:
-
请注意,即使存储
imtl而不是bigmap也会产生一个白色文件,而JFrame是不必要的,因此您仍然可以将这个示例剪掉很多。跨度>