Image save error

i've got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reaso...

i’ve got some binary data which i want to save as an image. When i try to save the image, it throws an exception if the memory stream used to create the image, was closed before the save. The reason i do this is because i’m dynamically creating images and as such .. i need to use a memory stream.

this is the code:

[TestMethod]
public void TestMethod1()
{
    // Grab the binary data.
    byte[] data = File.ReadAllBytes("Chick.jpg");

    // Read in the data but do not close, before using the stream.
    Stream originalBinaryDataStream = new MemoryStream(data);
    Bitmap image = new Bitmap(originalBinaryDataStream);
    image.Save(@"c:test.jpg");
    originalBinaryDataStream.Dispose();

    // Now lets use a nice dispose, etc...
    Bitmap2 image2;
    using (Stream originalBinaryDataStream2 = new MemoryStream(data))
    {
        image2 = new Bitmap(originalBinaryDataStream2);
    }

    image2.Save(@"C:temppewpew.jpg"); // This throws the GDI+ exception.
}

Does anyone have any suggestions to how i could save an image with the stream closed? I cannot rely on the developers to remember to close the stream after the image is saved. In fact, the developer would have NO IDEA that the image was generated using a memory stream (because it happens in some other code, elsewhere).

I’m really confused :(

Lasse V. Karlsen's user avatar

asked Dec 3, 2008 at 7:04

Pure.Krome's user avatar

Pure.KromePure.Krome

83.5k110 gold badges389 silver badges631 bronze badges

2

As it’s a MemoryStream, you really don’t need to close the stream — nothing bad will happen if you don’t, although obviously it’s good practice to dispose anything that’s disposable anyway. (See this question for more on this.)

However, you should be disposing the Bitmap — and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it «owns» the stream and you shouldn’t close it. As the docs for that constructor say:

You must keep the stream open for the
lifetime of the Bitmap.

I can’t find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.

Community's user avatar

answered Dec 3, 2008 at 7:12

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m851 gold badges9045 silver badges9133 bronze badges

4

A generic error occurred in GDI+.
May also result from incorrect save path!
Took me half a day to notice that.
So make sure that you have double checked the path to save the image as well.

displayName's user avatar

displayName

13.7k8 gold badges59 silver badges74 bronze badges

answered Apr 3, 2012 at 21:14

Houman's user avatar

2

Perhaps it is worth mentioning that if the C:Temp directory does not exist, it will also throw this exception even if your stream is still existent.

answered Oct 25, 2011 at 22:06

Rojzik's user avatar

RojzikRojzik

8828 silver badges8 bronze badges

1

Copy the Bitmap. You have to keep the stream open for the lifetime of the bitmap.

When drawing an image: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI

    public static Image ToImage(this byte[] bytes)
    {
        using (var stream = new MemoryStream(bytes))
        using (var image = Image.FromStream(stream, false, true))
        {
            return new Bitmap(image);
        }
    }

    [Test]
    public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()
    {
        var imageBytes = File.ReadAllBytes("bitmap.bmp");

        var image = imageBytes.ToImage();

        image.Save("output.bmp");
    }

Community's user avatar

answered Mar 31, 2010 at 18:55

Brian Low's user avatar

Brian LowBrian Low

11.5k4 gold badges58 silver badges63 bronze badges

2

I had the same problem but actually the cause was that the application didn’t have permission to save files on C. When I changed to «D:..» the picture has been saved.

answered Mar 11, 2014 at 21:24

Morad Aktam's user avatar

You can try to create another copy of bitmap:

using (var memoryStream = new MemoryStream())
{
    // write to memory stream here

    memoryStream.Position = 0;
    using (var bitmap = new Bitmap(memoryStream))
    {
        var bitmap2 = new Bitmap(bitmap);
        return bitmap2;
    }
}

answered Nov 19, 2013 at 10:59

Yuri Perekupko's user avatar

This error occurred to me when I was trying from Citrix. The image folder was set to C: in the server, for which I do not have privilege. Once the image folder was moved to a shared drive, the error was gone.

answered Jan 15, 2015 at 19:40

Jay K's user avatar

Jay KJay K

211 bronze badge

A generic error occurred in GDI+. It can occur because of image storing paths issues,I got this error because my storing path is too long, I fixed this by first storing the image in a shortest path and move it to the correct location with long path handling techniques.

answered Feb 7, 2014 at 8:07

S.Roshanth's user avatar

S.RoshanthS.Roshanth

1,4893 gold badges24 silver badges36 bronze badges

I was getting this error, because the automated test I was executing, was trying to store snapshots into a folder that didn’t exist. After I created the folder, the error resolved

answered Feb 7, 2017 at 15:16

P.Lisa's user avatar

One strange solution which made my code to work.
Open the image in paint and save it as a new file with same format(.jpg). Now try with this new file and it works. It clearly explains you that the file might be corrupted in someway.
This can help only if your code has every other bugs fixed

answered Feb 19, 2014 at 10:33

Vinothkumar's user avatar

It has also appeared with me when I was trying to save an image into path

C:Program Files (x86)some_directory

and the .exe wasn’t executed to run as administrator, I hope this may help someone who has same issue too.

answered Mar 27, 2017 at 15:31

Ali Ezzat Odeh's user avatar

Ali Ezzat OdehAli Ezzat Odeh

2,0631 gold badge17 silver badges17 bronze badges

For me the code below crashed with A generic error occurred in GDI+on the line which Saves to a MemoryStream. The code was running on a web server and I resolved it by stopping and starting the Application Pool that was running the site.

Must have been some internal error in GDI+

    private static string GetThumbnailImageAsBase64String(string path)
    {
        if (path == null || !File.Exists(path))
        {
            var log = ContainerResolver.Container.GetInstance<ILog>();
            log.Info($"No file was found at path: {path}");
            return null;
        }

        var width = LibraryItemFileSettings.Instance.ThumbnailImageWidth;

        using (var image = Image.FromFile(path))
        {
            using (var thumbnail = image.GetThumbnailImage(width, width * image.Height / image.Width, null, IntPtr.Zero))
            {
                using (var memoryStream = new MemoryStream())
                {
                    thumbnail.Save(memoryStream, ImageFormat.Png); // <= crash here 
                    var bytes = new byte[memoryStream.Length];
                    memoryStream.Position = 0;
                    memoryStream.Read(bytes, 0, bytes.Length);
                    return Convert.ToBase64String(bytes, 0, bytes.Length);
                }
            }
        }
    }

answered Dec 22, 2017 at 12:27

mortb's user avatar

mortbmortb

9,0613 gold badges25 silver badges43 bronze badges

I came across this error when I was trying a simple image editing in a WPF app.

Setting an Image element’s Source to the bitmap prevents file saving.
Even setting Source=null doesn’t seem to release the file.

Now I just never use the image as the Source of Image element, so I can overwrite after editing!

EDIT

After hearing about the CacheOption property(Thanks to @Nyerguds) I found the solution:
So instead of using the Bitmap constructor I must set the Uri after setting CacheOption BitmapCacheOption.OnLoad.(Image1 below is the Wpf Image element)

Instead of

Image1.Source = new BitmapImage(new Uri(filepath));

Use:

var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filepath);
image.EndInit();
Image1.Source = image;

See this: WPF Image Caching

answered Mar 16, 2018 at 8:25

mkb's user avatar

mkbmkb

1,0261 gold badge18 silver badges21 bronze badges

2

Try this code:

static void Main(string[] args)
{
    byte[] data = null;
    string fullPath = @"c:testimage.jpg";

    using (MemoryStream ms = new MemoryStream())
    using (Bitmap tmp = (Bitmap)Bitmap.FromFile(fullPath))
    using (Bitmap bm = new Bitmap(tmp))
    {
        bm.SetResolution(96, 96);
        using (EncoderParameters eps = new EncoderParameters(1))
        {   
            eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
            bm.Save(ms, GetEncoderInfo("image/jpeg"), eps);
        }

        data = ms.ToArray();
    }

    File.WriteAllBytes(fullPath, data);
}

private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
        ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

        for (int j = 0; j < encoders.Length; ++j)
        {
            if (String.Equals(encoders[j].MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase))
                return encoders[j];
        }
    return null;
}

answered Jul 30, 2018 at 16:24

BogdanRB's user avatar

BogdanRBBogdanRB

1581 silver badge5 bronze badges

I used imageprocessor to resize images and one day I got «A generic error occurred in GDI+» exception.

After looked up a while I tried to recycle the application pool and bingo it works. So I note it here, hope it help ;)

Cheers

answered Feb 12, 2020 at 8:10

Nick Hoàng's user avatar

Nick HoàngNick Hoàng

3721 silver badge6 bronze badges

I was getting this error today on a server when the same code worked fine locally and on our DEV server but not on PRODUCTION. Rebooting the server resolved it.

answered Sep 25, 2020 at 5:39

Kris's user avatar

KrisKris

4943 gold badges6 silver badges19 bronze badges

public static byte[] SetImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }
public static Bitmap SetByteToImage(byte[] blob)
    {
        MemoryStream mStream = new MemoryStream();
        byte[] pData = blob;
        mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
        Bitmap bm = new Bitmap(mStream, false);
        mStream.Dispose();
        return bm;
    }

answered Mar 22, 2021 at 4:17

Kong SiengPirot's user avatar

1

  • Remove From My Forums
  • Question

  • I just moved to VB 2015. Image save fails. Tested again with VB 2010 it works. I made sure that the directory and file are not write protected. Here is the code.

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim Img As New Bitmap(10, 10)
            Dim OpenFileDlg As New OpenFileDialog
            With OpenFileDlg
                .FileName = «»
                .DefaultExt = «.jpg|.JPG»
                .Filter = «(*.bmp, *.jpg)|*.bmp;*.jpg»
                .Multiselect = False
                If .ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                    Img = Bitmap.FromFile(.FileName)
                End If
                Img.Save(.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
            End With
        End Sub
    End Class

    Exception details :

    System.Runtime.InteropServices.ExternalException was unhandled
      ErrorCode=-2147467259
      HResult=-2147467259
      Message=A generic error occurred in GDI+.
      Source=System.Drawing
      StackTrace:
           at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
           at System.Drawing.Image.Save(String filename, ImageFormat format)
           at FileSaveTest.Form1.Form1_Load(Object sender, EventArgs e) in C:VBFileSaveTestForm1.vb:line 13
           at System.EventHandler.Invoke(Object sender, EventArgs e)
           at System.Windows.Forms.Form.OnLoad(EventArgs e)
           at System.Windows.Forms.Form.OnCreateControl()
           at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
           at System.Windows.Forms.Control.CreateControl()
           at System.Windows.Forms.Control.WmShowWindow(Message& m)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.Form.WmShowWindow(Message& m)
           at System.Windows.Forms.Form.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
      InnerException: 

    Any suddgestions ?

Answers

  • Tommy, 

    Got it, this runs and goes smooth

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim Img As New Bitmap(1, 1)
            Dim OpenFileDlg As New OpenFileDialog
            Dim SaveFileDlg As New SaveFileDialog
            With OpenFileDlg
                .FileName = ""
                .DefaultExt = ".jpg|.JPG"
                .Filter = "(*.bmp, *.jpg)|*.bmp;*.jpg"
                .Multiselect = False
                If .ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                    Dim fs As New IO.FileStream(.FileName, _
                IO.FileMode.Open)
                    Dim br As New IO.BinaryReader(fs)
                    Dim byteArray = br.ReadBytes(CInt(fs.Length))
                    br.Close()
                    Dim ms As New IO.MemoryStream(byteArray)
                    Img = DirectCast(Image.FromStream(ms), Bitmap)
                End If
            End With
            With SaveFileDlg
                .FileName = OpenFileDlg.FileName
                .DefaultExt = ".jpg|.JPG"
                .Filter = "(*.bmp, *.jpg)|*.bmp;*.jpg"
                If .ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                    Img.Save(.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
                End If
            End With
        End Sub
    End Class


    Success
    Cor

    • Marked as answer by

      Tuesday, May 10, 2016 11:26 AM

  3D Design Bootcamp

Learn how to go a layer deeper with your images quicker than ever. Join expert Kladi Vergine to learn how 3D can take your creativity to new heights and help you develop additional marketable skills.

Learn how to fix, «Photoshop could not complete your request because of a program error» when opening or saving files

When opening or saving image files, you get one of the following errors:

  • «Could not complete your request because of a program error.»
  • «Could not save as «yourfilename.psd» because of a program error.»

Program error while saving files

The ‘Photoshop could not save as «yourfilename.psd» because of a program error.’ error can occur for various reasons from layer compositing to improper system permissions.

Follow the below troubleshooting recommendations to resolve program errors while saving files in Photoshop.

Could not save as because of a program error

  1. Grant Photoshop «Full Disk Access» in macOS System Preferences

    To change this preference on your Mac, choose Apple menu  > System Preferences > Security & Privacy > then click Privacy. 
    See Change Privacy preferences on Mac

  2. Hide all layers in the Layers panel then Save again

    Click or click and drag across the visibility icon on each of the layers to hide them.

You can also use the deprecated macOS Save API to use the older, deprecated save methods.

Program error while opening files

The ‘Photoshop could not complete your request because of a program error’ error can occur for various reasons from damaged Photoshop preferences to incompatible system hardware or software.

Follow the below troubleshooting recommendations to resolve program errors while opening files in Photoshop.

Photoshop Program error

    • Navigate to Preferences > Plug-ins
    • Uncheck Enable Generator
  1. Reinstall your graphics driver

  2. Restore Photoshop’s default preferences

  3. Turn off GPU acceleration

Program Error Diagnostic Plugin

  1. Download and decompress the user-diagnostics.zip file to a local folder you will be able to locate

    Download

    Get file

    Download the User-diagnostics.zip file

  2. With the zip archive decompressed, copy the «user-diagnostic» folder to the Photoshop Plug-Ins folder at the following locations:

    1. macOS: Application Folder > Adobe Photoshop 2022 > Plug-Ins
    2. Windows: Program Files > Adobe> Adobe Photoshop 2022 > Plug-Ins

    Copy the user-diagnostics folder to Plug-ins

    Copy the user-diagnostics folder to Plug-ins
  3. Select “Photoshop User Diagnostics” from the Plugins menu.

  4. In the panel that appears, make sure “copy error stacks to clipboard” is checked.

  5. Perform your steps that reproduce the Program Error

  6. When the Program Error appears, click Ok. When the dialog is dismissed, more details on the error are added to your clipboard for easy pasting.

If you are trying to modify Bitmap, you may encounter the following GDI error which is very generic and does not provide any details. As the exception does not provide more details, it is very frustrating to figure out the root cause.

Bitmap.Save(): A generic error occurred in GDI+

2 Reasons Why This Generic GDI Error Occurred

GDI+ throws an error when it cannot save file. Following are 2 reasons why this error occurs.

  • When you are initializing a Bitmap object from an image stored on hard disk, it creates a lock on the underlying image file. Due to the lock when you try to save and overwrite your modified bitmap, it throws this error.
  • When you are saving a file, make sure the user has Write permission on the folder. This is important when you are getting this error on the Website because Website runs under restricted permissions.

There are three ways to fix this issue.

  • Instead of overwriting the file, save a new file with a different name than the original file
  • Only when the Bitmap object is disposed, the underlying lock on the file is removed. Once the lock is removed, you may overwrite the file. If you must overwrite the existing file, create a separate bitmap object from existing bitmap object. Now dispose the old bitmap object which will release the lock on the image file. Go ahead and make the needed changes in new bitmap object and save the new bitmap object with original image file name.
  • Make sure the folder in which you are trying to save file is writable. In Web Application, the application pool or account which runs the Website must have write access to to the folder in order to save the file. For example if you are running Website under “DefaultAppPool”, you must give “IIS AppPoolDefaultAppPool” user “write” access to the folder.

Sample Code That Causes Error

Dim oBitmap As Bitmap
oBitmap = New Bitmap("c:\example.jpg")
Dim oGraphic As Graphics
oGraphic = Graphics.FromImage(oBitmap)
Dim oBrush As New SolidBrush(Color.Black)
Dim ofont As New Font("Arial", 8 )
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)
oBitmap.Save("c:\example.jpg",ImageFormat.Jpeg)
oBitmap.Dispose()
oGraphic.Dispose()

As shown in the above example, I am reading the bitmap, modifying it and overwriting it on the same file. As the process creates a lock on the underlying image, it will throw an exception.

Sample Code With Fix

Dim oBitmap As Bitmap
oBitmap = New Bitmap("c:\example.jpg")
Dim oGraphic As Graphics
' Here create a new bitmap object of the same height and width of the image.
Dim bmpNew As Bitmap = New Bitmap(oBitmap.Width, oBitmap.Height)
oGraphic = Graphics.FromImage(bmpNew)
oGraphic.DrawImage(oBitmap, New Rectangle(0, 0, _
bmpNew.Width, bmpNew.Height), 0, 0, oBitmap.Width, _
oBitmap.Height, GraphicsUnit.Pixel)
' Release the lock on the image file. Of course,
' image from the image file is existing in Graphics object
oBitmap.Dispose()
oBitmap = bmpNew
 
Dim oBrush As New SolidBrush(Color.Black)
Dim ofont As New Font("Arial", 8 )
oGraphic.DrawString("Some text to write", ofont, oBrush, 10, 10)
oGraphic.Dispose()
ofont.Dispose()
oBrush.Dispose()
oBitmap.Save("c:\example.jpg", ImageFormat.Jpeg)
oBitmap.Dispose()

As shown in the above example, as soon as I create bitmap from an image, I am disposing the original bitmap. It releases the lock on the file. Hence I am able to overwrite the same file with updated bitmap.

Save for Web in Photoshop means that your images will be optimized for web use. That’s why a lot of web designers, graphic designers who create designs for the web use this command in Photoshop to better display their work. 

When you select Save for Web, you can export your images in a few different formats like JPEG, PNG, GIF, and BMP files. 

Table of Contents

  • How to Save for Web in Photoshop
  • 5 Quick Ways to Fix Save for Web Error in Photoshop
    • 1. Restart Photoshop
    • 2. Change image/canvas size
    • 3. Reset Photoshop Preferences
    • 4. Software/System Update
    • 5. Save as JPEG

Before finding out what goes wrong, make sure you’ve got the steps right. Let’s quickly go through the steps of how to use Save for Web in Photoshop. 

Note: the screenshots are taken from Adobe Photoshop CC 2021 Mac version. Windows or other versions can look different. 

Step 1: Go to the top menu File > Export > Save for Web (Legacy)

This window will pop up. I know it can look a bit complicated, but actually, there are only a few things you need to do. 

Step 2: Choose a format that you want to save, and other settings will adjust accordingly. For example, I chose JPEG. 

You’ll see that above the image window, there are the options 2-Up and 4-Up. Click on either one, it will show you the quality comparison of the image. 

You can adjust the image quality and compare the results. See the image quality, speed, and size at the bottom of the images. 

Step 3 (Optional): Change the image size. It’ll show how much percentage is the new size compared to the original one.

Step 4: If you’re happy with the look, click Save. Name the image and choose where you want it to locate and click Save

5 Quick Ways to Fix Save for Web Error in Photoshop

If you’ve used the same steps and still ran into trouble, check out some common solutions below.  

1. Restart Photoshop

The typical solution is restarting your Photoshop. Save your image in a .psd format before you restart in case you lose your original file. 

2. Change image/canvas size

Check if your image is larger than the canvas, try to set the image and canvas the same size from the top menu Image > Image Size.

3. Reset Photoshop Preferences

Go to the top menu and select Photoshop > Preferences > General. Click the Reset Preferences On Quit button. 

4. Software/System Update

Check if your Photoshop version, and if it’s out of date, go to the Creative Cloud app and update to the latest version. 

5. Save as JPEG

Actually, in the newer versions of Photoshop, when you save an image as a JPEG, it can be used for the web. If you want to make the size smaller, you can change the size from the top menu Image > Image Size.

Trying the solutions above should get your Save for Web error fixed. If you have other solutions, feel free to share 😉

June is an experienced graphic designer specializing in brand design. Photoshop is the essential tool that she uses every day along with other Adobe programs for her creative work.

Понравилась статья? Поделить с друзьями:
  • Ike error zastava как исправить
  • Image quality assessment from error visibility to structural similarity
  • Image onload error
  • Imm communication error
  • Image not available как исправить