查看更多java体系文档
png文件格式解析
生成一个下图示例的png图片
png图片二进制格式解析
生成png图java代码
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
public class WritePng {
public static void main(String[] args) throws IOException {
writePng();
}
private static void writePng() throws IOException {
File file = new File("a.png");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(new byte[]{(byte) 0x89,0x50,0x4e,0x47,0x0d,0x1a,0x0a});
fileOutputStream.write(pngChunkData(new byte[]{0x49,0x48,0x44,0x52},new byte[]{00,00,00,02,00,00,00,02,0x08,02,00,00,00}));
byte[] rgbData=new byte[]{00, (byte) 0xff,00,00,00,00, (byte) 0xff,00,00,00, (byte) 0xff, (byte) 0xff,00,00};
fileOutputStream.write(pngChunkData(new byte[]{0x49,0x44,0x41,0x54},deflateZip(rgbData)));
fileOutputStream.write(pngChunkData(new byte[]{0x49,0x45,0x4e, (byte) 0x44},null));
fileOutputStream.close();
System.out.println("操作成功");
}
private static byte[] deflateZip(byte[] source) {
Deflater deflater = new Deflater();
deflater.setInput(source);
deflater.finish();
byte[] tem=new byte[64];
byte[] dataByte=new byte[0];
int deflate=0;
while (!deflater.finished()){
deflate = deflater.deflate(tem);
byte[] array = ByteBuffer.allocate(deflate).put(tem, 0, deflate).array();
byte[] temByte=new byte[dataByte.length+array.length];
System.arraycopy(dataByte,0 , temByte, 0,dataByte.length );
System.arraycopy(array, 0, temByte, dataByte.length, array.length);
dataByte=temByte;
}
deflater.end();
return dataByte;
}
private static byte[] pngChunkData(byte[] chunkType,byte[] data) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int dataLength=0;
byte[] crcCheckSource= Arrays.copyOf(chunkType,chunkType.length);
if(data!=null){
dataLength=data.length;
baos.write(crcCheckSource);
baos.write(data);
crcCheckSource=baos.toByteArray();
baos.reset();
}
byte[] crcCheck = crc32CheckValue(crcCheckSource);
baos.write(ByteBuffer.allocate(4).putInt(dataLength).array());
baos.write(chunkType);
if(data!=null){
baos.write(data);
}
baos.write(crcCheck);
return baos.toByteArray();
}
private static byte[] crc32CheckValue(byte[] bytes) {
CRC32 crc32 = new CRC32();
crc32.update(bytes);
int value = (int) crc32.getValue();
return ByteBuffer.allocate(4).putInt(value).array();
}
}