- import java.awt.image.BufferedImage;
- import java.io.Closeable;
- import java.io.DataInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import javax.imageio.ImageIO;
- public class Test {
- public static void main(String[] args) throws IOException{
- // 需要编码的文本文件
- File file = new File("src/Test.java");
- // 编码后输出的图片文件流 文件名最好是png结尾
- OutputStream out = new FileOutputStream("test.png");
- // 编码到图片
- encode(file,out);
- // 从图片解码 图片后缀名必须是png
- decode(new File("test.png"),System.out);
- }
- /**
- * 将文本文件编码到图片
- * @param file 需要编码的文件
- * @param out 图片文件输出流
- */
- public static void encode(File file,OutputStream out) {
- if(file.isFile() && file.canRead()) {
- // 中文注释
- long length = file.length();
- double d = Math.sqrt(length / 3);
- int size = (int) Math.ceil(d);
- DataInputStream in = null;
- try{
- in = new DataInputStream(new FileInputStream(file));
- BufferedImage bi = new BufferedImage(size, size,BufferedImage.TYPE_3BYTE_BGR);
- over:
- for(int y=0;y<size;y++) {
- for(int x=0;x<size;x++) {
- int ch1 = in.read();
- int ch2 = in.read();
- int ch3 = in.read();
- if(-1 == ch1) {
- break over;
- }
- int rgb = (ch1 << 16)+(ch2==-1?0:(ch2 << 8)) + (ch3==-1?0:(ch3 << 0));
- bi.setRGB(x, y, rgb);
- if(-1 == ch3) {
- break over;
- }
- }
- }
- ImageIO.write(bi, "PNG", out);
- } catch(IOException ex) {
- } finally {
- try{
- close(in);
- }finally{
- close(out);
- }
- }
- }
- }
- /**
- * 从编码后的图片文件中解码成文本
- * @param file 需要解码的图片文件
- * @param out 解码后文本文件输出流
- */
- public static void decode(File file,OutputStream out) {
- if(file.isFile() && file.canRead()) {
- try{
- BufferedImage bi = ImageIO.read(file);
- int w = bi.getWidth();
- int h = bi.getHeight();
- for(int y=0;y<h;y++) {
- for(int x=0;x<w;x++) {
- int rgb = bi.getRGB(x, y);
- out.write(new byte[]{(byte)(rgb>>16),(byte)(rgb>>8),(byte)(rgb>>0) });
- }
- }
- } catch(IOException ex) {
- } finally {
- close(out);
- }
- }
- }
- /**
- * 关闭输入输出流
- * @param closeable
- */
- private static void close(Closeable closeable) {
- if(null != closeable) {
- try {
- closeable.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/061120136931.html
来源: http://www.codesnippet.cn/detail/061120136931.html