无法保存c#位图作为jpg

时间:2018-02-10 16:39:40

标签: c# bitmap draw

我试图将位图保存为jpg,但我无法管理。 它抛出了如下的重复

  

:System.Runtime.InteropServices.ExternalException:[ExternalException   (0x80004005):GDI +içindegenelbirhataoluştu。]   System.Drawing.Image.Save(String filename,ImageCodecInfo encoder,   EncoderParameters encoderParams)+477588
  httpdocs_Deneme.Page_Load(Object sender,EventArgs e)中   C:\的Inetpub \虚拟主机\ tufanyumlu.com \的httpdocs \ Deneme.aspx.cs:47
  System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,   EventArgs e)+51 System.Web.UI.Control.OnLoad(EventArgs e)+95
  System.Web.UI.Control.LoadRecursive()+59
  System.Web.UI.Page.ProcessRequestMain(布尔   includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)   678

我的代码块在

之下
protected void Page_Load(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    byte[] originalData = wc.DownloadData("http://tufanyumlu.com/images/00050-900x596.jpg");
    MemoryStream stream = new MemoryStream(originalData);
    Bitmap bitMapImage = new Bitmap(stream);
    Graphics graphicImage = Graphics.FromImage(bitMapImage);
    graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
    graphicImage.DrawLine(new Pen(Color.White, 65), 650, 560, 900, 560);
    graphicImage.DrawString("SgSHoBBy",
       new Font("Segoe Print", 22, FontStyle.Bold),
       SystemBrushes.WindowText, new Point(700, 530));
    Response.ContentType = "image/jpeg";
    var encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 1L);
    string uriPath = "http://www.tufanyumlu.com/images/deneme.jpg";
    string localPath = new Uri(uriPath).LocalPath;
    bitMapImage.Save(localPath, GetEncoder(ImageFormat.Jpeg), encoderParameters);
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    var codecs = ImageCodecInfo.GetImageDecoders();
    foreach (var codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

您的异常(英文中的gdi + 中发生了一般错误)是由BitMap.Save中的无效路径 - 方法调用或缺少访问权限引起的。在您的情况下,您尝试保存的路径为"/images/deneme.jpg"

您应该在代码中明确设置保存路径。您可以在应用程序的配置文件中添加图像保存根文件夹。所以你的Page_Load方法中的最后一行可能是:

var root = ConfigurationSettings.AppSettings["downloadRootPath"];
string localPath = root + new Uri(uriPath).LocalPath;
bitMapImage.Save(localPath, GetEncoder(ImageFormat.Jpeg), encoderParameters);

..您在 app.config web.config 中进行了以下配置,具体取决于运行时上下文:

<appSettings>
  <add key="downloadRootPath" value="C:\TEMP\"/>
</appSettings>

还要确保该文件夹存在且您的应用程序具有适当的访问权限。