c# 通过修改图片对象的文件的字节 变相"加密""解密"图片在磁盘的存储

实现思路比较简单:
1.对图片对象进行byteArray转化后 加一些密码字节后"加密"储存在磁盘
2.图片显示时 去掉加的字串 用原本的图片信息进行图片对象的构建和显示

WinForm下示例代码:
------------------
WinForm下通过PictureBox控件来显示:
只所以用PictureBox的Image对象
是因为有可能图像对象不是平时所见的已存在于磁盘的图片文件
还有可能是从视频采集卡等直接抓取的图像

//图像"加密"保存
private void button1_Click(object sender, EventArgs e)
{
    //把pictureBox1中的图像增加一些密码字节的文字信息后 "加密"储存在磁盘
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    byte[] byteArrayPwd = System.Text.Encoding.Default.GetBytes("http://freeliver54.cnblogs.com/");
    ms.Write(byteArrayPwd, 0, byteArrayPwd.Length);
    //   
    Image img = this.pictureBox1.Image;       
    //将图片对象存入MemoryStream
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);   
    //保存"图片"文件 此时的图片用平常的图片浏览器是不能正常打开查看的
    BinaryWriter bw = new BinaryWriter(File.Open(@"F:\\images\20081014.jpg", FileMode.OpenOrCreate));
    bw.Write(ms.ToArray());
    bw.Close();
    ms.Close();
}

//"解密"图像显示 注意该解密是在内存中进行 并没有通过中间的tmp文件来搭桥
private void button2_Click(object sender, EventArgs e)
{
    FileStream fs = new FileStream(@"F:\\images\20081014.jpg", FileMode.Open, FileAccess.Read);
    byte[] byteArrayFile = new byte[fs.Length];
    fs.Read(byteArrayFile, 0, (int)fs.Length);
    fs.Close();

     byte[] byteArrayPwd = System.Text.Encoding.Default.GetBytes("http://freeliver54.cnblogs.com/");
     System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayFile, byteArrayPwd.Length,byteArrayFile.Length-

byteArrayPwd.Length);
     //需要做相关异常处理 因为截取位置若不正确 将不能正常的构建出图像对象 会抛参数无效等异常
     try
     {
         this.pictureBox2.Image = System.Drawing.Image.FromStream(ms);
     }
     finally
     {
         ms.Close();
     }   
}

----
以上是在WinForm下的简单尝试
可能"加密"后的图片 要在Web页面的Image等控件来显示
此时就不能用直接的src指向图片文件 因为此时的该图片文件是不能正常显示的
可通过另外的页面对图片解密后再返回给控件进行显示<img src="Picture.aspx"> 

posted on 2008-10-14 14:55  freeliver54  阅读(2248)  评论(0编辑  收藏  举报

导航