2009-11-23 85 views
3

我得到了GDI發生保存圖像,在GDI發生一般性錯誤+

一般性錯誤+

例外,當我打電話img.Save(path, jpegCodec, encoderParams);
這裏是所有的代碼:

private Image img; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     this.img = Image.FromFile(@"path"); 

     pictureBox1.Image = img; 

     if (img.Height < pictureBox1.Height && img.Width < pictureBox1.Width) 
     { 
      this.pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; 
     } 

     Graphics g = Graphics.FromImage(img); 

     Font font=new Font("Arial",16); 

     SolidBrush brush = new SolidBrush(Color.Black); 

     brush.Color = Color.FromArgb(255, 0, 0, 255); 

     g.DrawString("myName", font, brush, img.Width - 178, img.Height-105); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     Bitmap bitmap = new Bitmap(img); 

     saveJpeg(@"path", bitmap, 85L); 
    } 

    private void saveJpeg(string path, Bitmap img, long quality) 
    { 
     // Encoder parameter for image quality 
     EncoderParameter qualityParam =new EncoderParameter(Encoder.Quality, quality); 

     // Jpeg image codec 
     ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg"); 

     if (jpegCodec == null) 
      return; 

     EncoderParameters encoderParams = new EncoderParameters(1); 
     encoderParams.Param[0] = qualityParam; 

     //img.Save(path, jpegCodec, encoderParams); 
     img.Save(path, jpegCodec, encoderParams); 
    } 
    private ImageCodecInfo getEncoderInfo(string mimeType) 
    { 
     // Get image codecs for all image formats 
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); 

     // Find the correct image codec 
     for (int i = 0; i < codecs.Length; i++) 
      if (codecs[i].MimeType == mimeType) 
       return codecs[i]; 
     return null; 
    } 

你能幫我嗎?

回答

7

只要通過從文件加載圖像創建的圖像對象存在,該文件就被使用。當文件正在使用時,您不能保存具有相同名稱的圖像。

代替使用Image.FromFile加載圖像,請打開文件流並使用Image.FromStream創建圖像,然後關閉文件流。這樣文件就不再使用了,你可以替換它。

0
public ActionResult CropImage(string hdnx, string hdny, string hdnw, string hdnh) 
{ 
    string fname = "pool.jpg"; 
    string fpath = Path.Combine(Server.MapPath("~/images"), fname); 
    Image oimg = Image.FromFile(fpath); 
    Rectangle cropcords = new Rectangle(
    Convert.ToInt32(hdnx), 
    Convert.ToInt32(hdny), 
    Convert.ToInt32(hdnw), 
    Convert.ToInt32(hdnh)); 
    string cfname, cfpath; 
    Bitmap bitMap = new Bitmap(cropcords.Width, cropcords.Height,img.PixelFormat); 

    Graphics grph = Graphics.FromImage(bitMap); 
    grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel); 
    cfname = "crop_" + fname; 
    cfpath = Path.Combine(Server.MapPath("~/cropimages"), cfname); 
    bitMap.Save(cfpath); 

    return Json("success",JsonRequestBehavior.AllowGet); 
} 
+0

請指導OP如何解決他的問題 – 2014-08-01 06:00:06