我正在尝试使用IndexColorModel在Java中创建一个2位/ 4色位图。但是,当我运行代码时,我似乎遇到了错误。
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.image.IndexColorModel;
public class bitmaptest {
public static void main(String[] args) {
String text = "اردو لکھیئے";
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Arabic Typesetting", Font.PLAIN, 48);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width = fm.stringWidth(text);
int height = fm.getHeight();
g2d.dispose();
Color[] colors = {Color.red, Color.green, Color.yellow,
Color.black};
byte[] reds = new byte[4];
byte[] greens = new byte[4];
byte[] blues = new byte[4];
for (int i = 0; i < colors.length; i++) {
reds[i] = (byte) colors[i].getRed();
greens[i] = (byte) colors[i].getGreen();
blues[i] = (byte) colors[i].getBlue();
}
IndexColorModel cm = new IndexColorModel(2, 4, reds, greens, blues);
BufferedImage img2 = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY, cm);
g2d = img2.createGraphics();
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.red);
g2d.drawString(text, 0, fm.getAscent());
g2d.dispose();
try {
ImageIO.write(img2, "BMP", new File("Text.bmp"));
System.out.println(img2);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
我得到的错误是:
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.io.RandomAccessFile.writeBytes0(Native Method)
at java.io.RandomAccessFile.writeBytes(Unknown Source)
at java.io.RandomAccessFile.write(Unknown Source)
at javax.imageio.stream.FileImageOutputStream.write(Unknown Source)
at com.sun.imageio.plugins.bmp.BMPImageWriter.write(Unknown Source)
at javax.imageio.ImageWriter.write(Unknown Source)
at javax.imageio.ImageIO.doWrite(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at bitmaptest.main(bitmaptest.java:51)
我非常感谢任何帮助。谢谢。
答案 0 :(得分:0)
将IndexColorModel颜色分量数组的大小更改为2或更小
IndexColorModel cm = new IndexColorModel(4, 2, reds, greens, blues);
或将Image类型从BufferedImage第三个参数构造函数调用更改为:
new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, cm);
文档提供了这些参数说明,可以让您更清楚地了解正在发生的事情:
public IndexColorModel(int bits, int size, byte [] cmap, int start, boolean hasalpha)
bits - the number of bits each pixel occupies size - the size of the color component arrays cmap - the array of color components start - the starting offset of the first color component hasalpha - indicates whether alpha values are contained in the cmap array