Skip to content

Instantly share code, notes, and snippets.

@sugyan
Created May 26, 2016 09:32
Show Gist options
  • Save sugyan/fa8391fb2b2da68ee981a5962d58e834 to your computer and use it in GitHub Desktop.
Save sugyan/fa8391fb2b2da68ee981a5962d58e834 to your computer and use it in GitHub Desktop.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream("./data_batch_1.bin");
byte[] b = new byte[3073];
inputStream.read(b);
BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
for (int row = 0; row < 32; row++) {
for (int col = 0; col < 32; col++) {
Color color = new Color(
b[1 + 1024 * 0 + row * 32 + col] & 0xFF,
b[1 + 1024 * 1 + row * 32 + col] & 0xFF,
b[1 + 1024 * 2 + row * 32 + col] & 0xFF);
image.setRGB(col, row, color.getRGB());
}
}
boolean result = ImageIO.write(image, "jpeg", new FileOutputStream("./out.jpg"));
if (!result) {
System.err.println("failed");
}
}
}
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) throws IOException {
BufferedImage bufferedImage = ImageIO.read(new File("./image.jpg"));
assert bufferedImage.getHeight() == 32;
assert bufferedImage.getWidth() == 32;
assert bufferedImage.getColorModel().getNumComponents() == 3;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write((byte) 0);
for (int i = 0; i < 3; i++) {
for (int row = 0; row < bufferedImage.getHeight(); row++) {
for (int col = 0; col < bufferedImage.getWidth(); col++) {
Color color = new Color(bufferedImage.getRGB(col, row));
switch (i) {
case 0:
outputStream.write(color.getRed());
break;
case 1:
outputStream.write(color.getGreen());
break;
case 2:
outputStream.write(color.getBlue());
break;
default:
break;
}
}
}
}
assert outputStream.size() == 3073;
outputStream.writeTo(new FileOutputStream("./out.bin"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment