我创建了一个简单的类,它将bytes
的{{1}}编码为BufferedImage
的像素。我正在使用一个字节数组,并在写出图像时将每4 bytes
打包成ARGB
值。我觉得有一种更简单的方法可以做到这一点。我有更好的存储像素数据的方法吗?
代码生成这个微小的图像,但它可以缩放导出*任何*大小→ ←
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PixelExport {
private byte[] data;
private static byte f(int value) { return (byte) value; }
private static long pack(byte b1, byte b2, byte b3, byte b4) {
return ((0xFFL & b1) << 24) | ((0xFFL & b2) << 16) |
((0xFFL & b3) << 8) | (0xFFL & b4);
}
public PixelExport() {
data = new byte[] {
// Row 1 - Red with Alpha FF -> 3F
f(0xFF), f(0xFF), f(0x00), f(0x00),
f(0xBF), f(0xFF), f(0x00), f(0x00),
f(0x7F), f(0xFF), f(0x00), f(0x00),
f(0x3F), f(0xFF), f(0x00), f(0x00),
// Row 1 - Green with Alpha FF -> 3F
f(0xFF), f(0x00), f(0xFF), f(0x00),
f(0xBF), f(0x00), f(0xFF), f(0x00),
f(0x7F), f(0x00), f(0xFF), f(0x00),
f(0x3F), f(0x00), f(0xFF), f(0x00),
// Row 1 - Blue with Alpha FF -> 3F
f(0xFF), f(0x00), f(0x00), f(0xFF),
f(0xBF), f(0x00), f(0x00), f(0xFF),
f(0x7F), f(0x00), f(0x00), f(0xFF),
f(0x3F), f(0x00), f(0x00), f(0xFF)
};
export(data, 4, 3, "foo", "png");
}
public void export(byte[] data, int width, int height, String filename, String ext) {
String fullFilename = String.format("%s.%s", filename, ext);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < data.length; i+=4) {
int row = i / (width * 4);
int col = (i / 4) % width;
image.setRGB(col, row, (int) pack(data[i], data[i+1], data[i+2], data[i+3]));
}
try {
ImageIO.write(image, ext, new File(fullFilename));
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.printf("Wrote: %s\n", fullFilename);
}
}
public static void main(String[] args) {
new PixelExport();
}
}
我也可以使用ByteBuffer
,但这是必要的吗?如果我已经有指数?
ByteBuffer buf = ByteBuffer.wrap(data);
buf.rewind();
while (buf.hasRemaining()) {
int row = buf.position() / (width * 4);
int col = (buf.position() / 4) % width;
image.setRGB(col, row, (int) pack(buf.get(), buf.get(), buf.get(), buf.get()));
}