简体   繁体   中英

Saving Bitmap leads to Generic GDI+ error

I've been searching around for a solution to this but haven't really found one. Here is some patchwork code that I've been playing with trying to get this working but no success.

private Image GetAlbumArt(String url)
{
    byte[] rBytes;
    Image Testing;
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
    WebResponse myResponse = myRequest.GetResponse();
    Stream rStream = myResponse.GetResponseStream();
    using (BinaryReader br = new BinaryReader(rStream))
    {
        rBytes = br.ReadBytes(1000000);
        br.Close();
    }
    myResponse.Close();

    using (MemoryStream imageStream = new MemoryStream(rBytes, 0, rBytes.Length))
    {
        imageStream.Write(rBytes, 0, rBytes.Length);
        Testing = Image.FromStream(imageStream, true);
        Testing.Save("temp.jpg"); //Error here!
    }
    return Testing;
}

I would actually rather not save the bitmap and just return the bitmap to the parent function, but that didnt work either. (cannot close the memory stream if you want to use the bitmap)

The really strange thing is that this works fine if i give it a different jpg url.

Doesnt work: http://2.images.napster.com/mp3s/2492/resources/207/116/files/207116316.jpg

works: http://3.images.napster.com/mp3s/2256/resources/301/404/files/301404546.jpg

Typically this is a permissions error.

Whenever I experience this problem I often find it to be down to trying to save to an invalid or inaccessible path.

Sticking a breakpoint on your save function, examining the output path, and then trying to access this same path through the file explorer is a quick way to verify you haven't misspelled anything. If it does exist I would then check permissions.

Hope that helps

I found if I save your image to bmp and it works fine. I also checked the DPI of your first image is much higher than the second one. Hope this is the clue you can go through.

Well, here is a snippet from some code I wrote to do the same thing

WebClient webClient = new WebClient();
using (Stream stream = webClient.OpenRead(imgeUri))
{
   using (Bitmap bitmap = new Bitmap(stream))
   {
      stream.Flush(); // not really necessary, but doesnt hurt
      stream.Close();
      try
      {
         // now, lets save to a memory stream and
         // return the byte[]
         MemoryStream ms = new MemoryStream();

         // doesnt have to be a Png, could be whatever you want (jpb, bmp, etc.)
         bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
         return ms.GetBuffer()
      }
      catch (Exception err)
      {
         Console.WriteLine("{0}\t\tError: {1}", id, err.Message);
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM