Created
June 15, 2016 17:37
-
-
Save Wieku/bc2f9d37ccfd5cba7f9a28852d8030ec to your computer and use it in GitHub Desktop.
This file contains 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 javax.imageio.ImageIO; | |
import java.awt.Color; | |
import java.awt.image.BufferedImage; | |
import java.io.File; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Scanner; | |
public class Main { | |
public static void main(String[] args) { | |
if(args.length == 0) { | |
System.out.println("No arguments given!"); | |
System.out.println("\"command encode\" - to encode text and save as out.png"); | |
System.out.println("\"command [PATH]\" - to decode given file and print to console"); | |
System.exit(0); | |
} | |
try { | |
String tempString = ""; | |
ArrayList<Color> colors = new ArrayList<>(); | |
BufferedImage img; | |
if(args[0].equals("encode")) { | |
System.out.println("Write something in ASCII:"); | |
Scanner in = new Scanner(System.in); | |
String input = in.nextLine(); | |
in.close(); | |
for(char har : input.toCharArray()) | |
tempString += getNumber(har); | |
int rgb=0, stg=0; | |
while (tempString.length() > 0) { | |
int num = Integer.valueOf(String.format("%1$-8s",tempString.substring(0,Math.min(8, tempString.length()))).replace(" ", "0"), 2); | |
tempString = tempString.substring(Math.min(8, tempString.length())); | |
if(stg==3) { | |
colors.add(new Color(rgb | num<<24, true)); | |
rgb = 0; stg = -1; | |
} else rgb |= num << (8*(2-stg)); | |
++stg; | |
} | |
if(stg != 0) | |
colors.add(new Color(rgb, true)); | |
img = new BufferedImage(colors.size(), 1, BufferedImage.TYPE_INT_ARGB); | |
for(int i=0; i<colors.size(); i++) | |
img.setRGB(i, 0, colors.get(i).getRGB()); | |
ImageIO.write(img, "png", new File("out.png")); | |
} else { | |
img = ImageIO.read(new File(args[0])); | |
for(int i=0; i < img.getWidth(); i++) { | |
Color color = new Color(img.getRGB(i, 0), true); | |
tempString += get8Number(color.getRed()) + get8Number(color.getGreen()) + get8Number(color.getBlue()) + get8Number(color.getAlpha()); | |
} | |
while (tempString.length() > 0) { | |
int num = Integer.valueOf(tempString.substring(0, Math.min(7, tempString.length())), 2); | |
tempString = tempString.substring(Math.min(7, tempString.length())); | |
System.out.print((char)num); | |
} | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static String getNumber(char chr) { | |
return String.format("%7s", Integer.toBinaryString((int)chr)).replace(" ", "0"); | |
} | |
public static String get8Number(int num) { | |
return String.format("%8s", Integer.toBinaryString(num)).replace(" ", "0"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment