将数据写入PNG文件并保证png能正常浏览

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;


public class PNGEncoder {
 /**
  * @author qpaber
  * PNG解码类 用于将数据写入PNG文件
  */
 private static final byte[] _PNGEND = {(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
             (byte)0x49,(byte)0x45,(byte)0x4E,(byte)0x44};
 
 /**
  * 将字符串写入PNG文件
  * @param f PNG文件
  * @param str 需要写入的文本信息
  */
 public static void writePNG(File f,String str){
  RandomAccessFile raf = null;
  FileInputStream tmpIn = null;
  FileOutputStream tmpOut = null;
  try{
   raf = new RandomAccessFile(f, "rw");
   File tmp = File.createTempFile("tmp", null);
   tmpIn = new FileInputStream(tmp);
   tmpOut = new FileOutputStream(tmp);
   
   //循环将PNG信息写入临时文件
   byte[] bbuf = new byte[12];
   int hasRead = 0;
   int i=0;
   raf.seek(0);
   while((hasRead = raf.read(bbuf))>0){
    if(isEND(bbuf)){
     tmpOut.write(bbuf,0,hasRead);
     break;
    }else{
     tmpOut.write(bbuf,0,1);
    }
    i=i+1;
    raf.seek(i);
   }
   //将字符串追加到临时文件
   tmpOut.write(str.getBytes());
   //将临时文件内容写入PNG文件
   raf.close();
   f.delete();
   raf = new RandomAccessFile(f, "rw");
   bbuf = new byte[1024];
   raf.seek(0);
   while((hasRead = tmpIn.read(bbuf)) > 0){
    raf.write(bbuf,0,hasRead);
   }
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try{
    if(raf!=null){
     raf.close();
     raf=null;
    }
    if(tmpIn!=null){
     tmpIn.close();
     tmpIn=null;
    }
    if(tmpOut!=null){
     tmpOut.close();
     tmpOut=null;
    }
   }catch(Exception e){
    e.printStackTrace();
   }
  }
 }
 /**
  * 是否为结束符
  * @param bbuf 需判断的byte[]
  * @return 是 true
  */
 private static boolean isEND(byte[] bbuf){
  if(bbuf[0] == _PNGEND[0] && bbuf[1] == _PNGEND[1] && bbuf[2] == _PNGEND[2] && bbuf[3] == _PNGEND[3] && 
    bbuf[4] == _PNGEND[4] && bbuf[5] == _PNGEND[5] && bbuf[6] == _PNGEND[6] && bbuf[7] == _PNGEND[7]){
   return true;
  }
  return false;
 }
 
 public static void main(String[] args){
  writePNG(new File("12.png"),"wkwwkwkwkwkwkwkwkwkwkwkwkwkwkwkwk");
  System.out.println("ok");
 }
}

转载于:https://www.cnblogs.com/ekaiser/archive/2012/11/07/2758106.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值