Skip to content

Instantly share code, notes, and snippets.

@hageldave
Created April 24, 2017 21:15
Show Gist options
  • Save hageldave/40bb7edaf878a63627cf462d24e7e6a5 to your computer and use it in GitHub Desktop.
Save hageldave/40bb7edaf878a63627cf462d24e7e6a5 to your computer and use it in GitHub Desktop.
loads and saves image data from and to a byte array
private static byte[] saveImgToBytes(Img img) {
int w = img.getWidth();
int h = img.getHeight();
int n = img.numValues();
int length = n*4 + 4+4;
byte[] b = new byte[length];
// save width
int i = 0;
b[i++] = signedByteToByte(w);
b[i++] = signedByteToByte(w>>8);
b[i++] = signedByteToByte(w>>16);
b[i++] = signedByteToByte(w>>24);
// save height
b[i++] = signedByteToByte(h);
b[i++] = signedByteToByte(h>>8);
b[i++] = signedByteToByte(h>>16);
b[i++] = signedByteToByte(h>>24);
// save pixel data
for(int color: img.getData()){
b[i] = signedByteToByte(Pixel.r(color));
b[i+n] = signedByteToByte(Pixel.g(color));
b[i+n*2] = signedByteToByte(Pixel.b(color));
b[i+n*3] = signedByteToByte(Pixel.a(color));
i++;
}
return b;
}
private static Img loadImgFromBytes(byte[] data) {
int w=0, h=0;
int i = 0;
// read width
w |= byteToSignedByte(data[i++]);
w |= byteToSignedByte(data[i++])<<8;
w |= byteToSignedByte(data[i++])<<16;
w |= byteToSignedByte(data[i++])<<24;
// read height
h |= byteToSignedByte(data[i++]);
h |= byteToSignedByte(data[i++])<<8;
h |= byteToSignedByte(data[i++])<<16;
h |= byteToSignedByte(data[i++])<<24;
// read pixel data
int n = w*h;
int[] pixels = new int[n];
for(int j = 0; j < pixels.length; j++,i++){
int r = byteToSignedByte(data[i]);
int g = byteToSignedByte(data[i+n]);
int b = byteToSignedByte(data[i+n*2]);
int a = byteToSignedByte(data[i+n*3]);
pixels[j] = Pixel.argb(a, r, g, b);
}
return new Img(w,h,pixels);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment