Created
March 19, 2013 19:15
-
-
Save TheBatScripts/5199232 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.awt.image.BufferedImage; | |
| import java.io.ByteArrayInputStream; | |
| import java.io.ByteArrayOutputStream; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import java.io.ObjectInputStream; | |
| import java.io.ObjectOutputStream; | |
| import javax.imageio.ImageIO; | |
| public class ObjectToImage{ | |
| public static void main(String[] args){ | |
| BufferedImage img = encode(new Polygon(new int[]{1,2,3,4,5,6,5,4,3,2},new int[]{1,1,3,4,5,6,7,8,9,10}, 10)); | |
| try { | |
| ImageIO.write(img, "png", new File("./img.png")); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } | |
| System.out.println((Polygon)decode(img)); | |
| } | |
| public static byte[] serialize(Object obj) throws IOException { | |
| ByteArrayOutputStream b = new ByteArrayOutputStream(); | |
| ObjectOutputStream o = new ObjectOutputStream(b); | |
| o.writeObject(obj); | |
| return b.toByteArray(); | |
| } | |
| public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException { | |
| ByteArrayInputStream b = new ByteArrayInputStream(bytes); | |
| ObjectInputStream o = new ObjectInputStream(b); | |
| return o.readObject(); | |
| } | |
| public static BufferedImage encode(Object o){ | |
| byte[] list = null; | |
| try { | |
| list = serialize(o); | |
| } catch (IOException e) { | |
| } | |
| BufferedImage img = new BufferedImage((int)Math.sqrt(list.length), (int)Math.sqrt(list.length)+1, BufferedImage.TYPE_INT_ARGB); | |
| img.setRGB(0, 0, list.length); | |
| int k = 0; | |
| out: for(int y = 0; y < img.getHeight(); y++){ | |
| for(int x = 0; x < img.getWidth(); x++){ | |
| if(x == 0 && y == 0)continue; | |
| img.setRGB(x, y, list[k++]); | |
| if(k == list.length)break out; | |
| } | |
| } | |
| return img; | |
| } | |
| public static Object decode(BufferedImage img){ | |
| byte[] list = new byte[img.getRGB(0,0)]; | |
| int k = 0; | |
| out: for(int y = 0; y < img.getHeight(); y++){ | |
| for(int x = 0; x < img.getWidth(); x++){ | |
| if(x == 0 && y == 0)continue; | |
| list[k++] = (byte) img.getRGB(x, y); | |
| if(k == list.length)break out; | |
| } | |
| } | |
| Object ob = null; | |
| try { | |
| ob = deserialize(list); | |
| } catch (ClassNotFoundException e) {} | |
| catch (IOException e) {} | |
| return ob; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment