现在的位置: 首页 > 综合 > 正文

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

2013年06月08日 ⁄ 综合 ⁄ 共 1529字 ⁄ 字号 评论关闭

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"> 

抱歉!评论已关闭.