怎样把修改后的图象保存到原图?

来源:互联网 发布:淘宝卖电器都要3c吗 编辑:程序博客网 时间:2024/05/04 23:31

如果我们打开一幅图象,修改这幅图象后,然后用与原图象相同的格式将文件保存在原来的路径上或者换一种格式来保存!这时,系统会提示我们“GDI+发生一般性错误”,这个问题是怎样产生的呢?
这个问题的产生,我们可以简单的说明下:
这是因为GDI+在读取图象文件时只是读取该图象文件的头部分!这样,你能了解这幅图的信息,包括该文件图象的宽度、高度和颜色深度信息等.在整个图象文件的生存周期中,总是保持对此图象文件处于打开状态,并且锁定此状态不让别的进程来试图再打开此文件。这样,你不能用修改过的图象来替换原文档!
那么,为了将修改过的图象写回原路径,你必须释放原图象的资源,否则保存图象时候将会出错!
具体过程如下:
1、打开图象文件
2、在内存中创建一个和原图象同样大小的位图文件
3、利用这个位图文件建立Graphics对象
4、把欲处理的图象绘制到位图文件上
5、释放图象文件所占用的资源
6、用Graphics的功能修改位图文件
7、释放Graphics对象资源
8、将位图文件以你所想要的格式保存
下述程序实现了文件格式转化功能,并以给图象增加时间戳来验证这一技术。程序设计界面如下:
                                  
使用方法:
1、单击 "Choose files"以选择一幅或者多幅图象文件。
2、在下拉框中选择文件保存格式!
3、确定是否给打开的图象文件加时间戳,然后单击"Convert" 命令按狃!
说明:如果你选择了JPEG格式的文件,并加了时间戳,并选择保存文件为JPEG格式,那么这将对原图象进行修改(加了个时间戳),注意不要对你想要保留的文件进行上述操作!
实现上述功能的代码如下:
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace FormatConvertor
{
  /// <summary>
  /// Summary description for Form1.
  /// </summary>
  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.ComboBox comboBox1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.CheckBox checkBox1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;
    public Form1()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }
    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.button1 = new System.Windows.Forms.Button();
      this.comboBox1 = new System.Windows.Forms.ComboBox();
      this.button2 = new System.Windows.Forms.Button();
      this.label1 = new System.Windows.Forms.Label();
      this.checkBox1 = new System.Windows.Forms.CheckBox();
      this.SuspendLayout();
      //
      // button1
      //
      this.button1.Location = new System.Drawing.Point(8, 24);
      this.button1.Name = "button1";
      this.button1.TabIndex = 0;
      this.button1.Text = "Choose files";
      this.button1.Click += new System.EventHandler(this.button1_Click);
      //
      // comboBox1
      //
      this.comboBox1.Items.AddRange(new object[] {
                               "GIF",
                               "JPG",
                               "JPEG",
                               "BMP",
                               "PNG"});
      this.comboBox1.Location = new System.Drawing.Point(96, 24);
      this.comboBox1.Name = "comboBox1";
      this.comboBox1.Size = new System.Drawing.Size(121, 21);
      this.comboBox1.TabIndex = 1;
      //
      // button2
      //
      this.button2.Location = new System.Drawing.Point(232, 24);
      this.button2.Name = "button2";
      this.button2.TabIndex = 0;
      this.button2.Text = "Convert";
      this.button2.Click += new System.EventHandler(this.button2_Click);
      //
      // label1
      //
      this.label1.Location = new System.Drawing.Point(96, 8);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(100, 16);
      this.label1.TabIndex = 2;
      this.label1.Text = "Output format";
      //
      // checkBox1
      //
      this.checkBox1.Location = new System.Drawing.Point(8, 64);
      this.checkBox1.Name = "checkBox1";
      this.checkBox1.Size = new System.Drawing.Size(208, 24);
      this.checkBox1.TabIndex = 3;
      this.checkBox1.Text = "Time stamp the image.";
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(312, 93);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.checkBox1,
                                      this.label1,
                                      this.comboBox1,
                                      this.button1,
                                      this.button2});
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
      this.Name = "Form1";
      this.Text = "Image Format Converter";
      this.ResumeLayout(false);
   }
    #endregion
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.Run(new Form1());
    }
    string[] names;
    bool chosen=false;
    private void button1_Click(object sender, System.EventArgs e)
    {
      OpenFileDialog dlg = new OpenFileDialog();
      dlg.Filter="Image files (*.jpg,*.jpeg,*.bmp,*.gif,*.png)|*.BMP;*.PNG;*.JPG;*.JPEG;*.PNG";
      dlg.Multiselect=true;
      if(dlg.ShowDialog()==DialogResult.OK)
      {
        chosen=true;
        names=dlg.FileNames;
      }
    }
    private void button2_Click(object sender, System.EventArgs e)
    {
       if(chosen && this.comboBox1.Text!="")
      {
        chosen=false;
        foreach(string s in names)
        {
          //open the file
          Image i = Image.FromFile(s);
          //create temporary
          Image t=new Bitmap(i.Width,i.Height);
          //get graphics
          Graphics g=Graphics.FromImage(t);
          //copy original
          g.DrawImage(i,0,0);
          //close original
          i.Dispose();
          if(this.checkBox1.Checked==true)
          {
            //draw on temporary
            Font f = new Font("Verdana",30);
            g.DrawString(DateTime.Now.ToShortDateString()+":"+DateTime.Now.ToShortTimeString(),
              f,
              Brushes.Red,
              10,10,
              StringFormat.GenericTypographic);
            f.Dispose();
          }
          g.Dispose();
          ImageFormat fmt = ImageFormat.Bmp;
          switch(this.comboBox1.Text)
          {
            case "JPG":
            case "JPEG":
              fmt=ImageFormat.Jpeg;
              break;
            case "GIF":
              fmt=ImageFormat.Gif;
              break;
            case "PNG":
              fmt=ImageFormat.Png;
              break;
         }
          //save the file. Even if its the same filename
          t.Save(Path.GetFileNameWithoutExtension(s)+"."+this.comboBox1.Text,fmt); 
        }
      }
    }
  }
}

原创粉丝点击