使用IndexColorModel在Java中创建2位/4色位图
我正在尝试使用IndexColorModel在Java中创建一个2位/4色位图。但是,当我运行代码时,似乎出现了一个错误使用IndexColorModel在Java中创建2位/4色位图,java,Java,我正在尝试使用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; i
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();
}
}
}
我将非常感谢所有的帮助。谢谢。将IndexColorModel颜色组件数组的大小更改为2或更小
IndexColorModel cm = new IndexColorModel(4, 2, reds, greens, blues);
或者将图像类型从BuffereImage第三个参数构造函数调用更改为:
new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, cm);
文档中给出了这些参数说明,这些说明应能让您更清楚地了解正在发生的情况:
公共IndexColorModel位,
整数大小,
字节[]cmap,
int start,
布尔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
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