Skip to content

Instantly share code, notes, and snippets.

@lorenzoongithub
Created June 3, 2016 21:09
Show Gist options
  • Save lorenzoongithub/dace58ea8dde941a21209c0fbba4561e to your computer and use it in GitHub Desktop.
Save lorenzoongithub/dace58ea8dde941a21209c0fbba4561e to your computer and use it in GitHub Desktop.
requires okio.jar in your classpath. see: https://github.com/square/okio
//
// PNG Encoder. This script requires okio.jar
//
var URL = Java.type('java.net.URL');
var ByteString = Java.type('okio.ByteString');
var Okio = Java.type('okio.Okio');
var Buffer = Java.type('okio.Buffer');
var url = new URL('http://i936.photobucket.com/albums/ad204/0_Marathon_0/Abstract.png');
var PNG_HEADER = ByteString.decodeHex("89504e470d0a1a0a");
var pngSource = Okio.buffer(Okio.source(url.openStream()));
var header = pngSource.readByteString(PNG_HEADER.size());
if (!header.equals(PNG_HEADER)) {
throw "Not a PNG.";
}
var str =''
while (true) {
var chunk = new Buffer();
// Each chunk is a length, type, data, and CRC offset.
var length = pngSource.readInt();
var type = pngSource.readUtf8(4);
pngSource.readFully(chunk, length);
var crc = pngSource.readInt();
if (type == "IHDR" ) {
var width = chunk.readInt();
var height = chunk.readInt();
str+= chunk.size()+' '+ type+' '+ width+' '+height +'\n';
} else {
str += chunk.size()+' '+ type+'\n';
// System.out.printf("%08x: %s%n", chunk.size(), type);
}
if (type.equals("IEND")) break;
}
pngSource.close();
str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment