-1

I am currently pulling VARBINARY data from an sql database, converting this to BITMAP and then adding each one of these to a List object.

However when i try to save each of the images in the above list, i get a generic GDI+ exception on the image.save function.

What i've tried:
- Changing paths (Path is currently C:\Temp for testing)
- Checking permissions (path has full permission)
- Changing from a list of BITMAP to a list of IMAGE - Changing the ImageFormat of the save function - Setting the EncodingQuality of the save function

A 0KB image is created in the correct directory with the correct name, so not quite sure what is causing the issue.

Below is my code for saving:

public void doImport(List<Bitmap> images, string certNo, string saveLoc, ListView.ListViewItemCollection items) {
        string path = String.Format("{0}\\{1}", saveLoc, certNo);

        if ( !Directory.Exists(path) ) { Directory.CreateDirectory(path); }

        for ( int i = 0; i < items.Count; i++ ) {
            Bitmap image = images[i];
            string imgPath = String.Format("{0}\\{1}\\{1}-{2}.jpg", saveLoc, certNo, items[i].Text);

            try {
                image.Save(imgPath, ImageFormat.Jpeg);
                if ( File.Exists(imgPath) ) { images.Remove(image); }
            } catch (Exception ex) {
                MessageBox.Show(String.Format("Warning: Could not save image: {0}, it has been skipped.\n\n{1}", items[i].Text, ex.Message), 
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

Thanks

Daniel
  • 31
  • 5
  • 1
    At a guess: you disposed of the stream you read the `Bitmap` from when you loaded it. See [this question](https://stackoverflow.com/questions/15862810/a-generic-error-occurred-in-gdi-in-bitmap-save-method) if that's the case. – ProgrammingLlama Jan 24 '20 at 04:06
  • Thanks, you pointed me in the right direction. – Daniel Jan 24 '20 at 04:24
  • also souldnt `if ( File.Exists(imgPath) ) { images.Remove(image); }` be before save? – Seabizkit Jan 24 '20 at 04:37

1 Answers1

2

Simple fix after reading a few similar questions. Just changed this line:

for ( int i = 0; i < items.Count; i++ ) {
        Bitmap image = images[i];

To this line:

for ( int i = 0; i < items.Count; i++ ) {
        Bitmap image = new Bitmap(images[i]);

Thanks :)

Daniel
  • 31
  • 5