Serialize, Deserialize, and Save Image Feedback

Here is my code for Serialize, Deserialize and save the image in the file system. I have reviewed many examples of serialization / deserialization, and I just want to get some feedback, as I am sure that my code can be improved. Any feedback would be greatly appreciated. I know this is a common problem, so hopefully this question will become a good resource for others in the future.

This is a redesigned code with recommendations:

private void Form1_Load(object sender, EventArgs e) { RunTest(); } private void RunTest() { byte[] jpgba = ConvertFileToByteArray("D:\\Images\\Image01.jpg"); using (Image jpgimg = ConvertByteArrayToImage(jpgba)) { SaveImageToFileSystem(jpgimg, "D:\\Images\\Image01_Copy.jpg"); } byte[] pngba = ConvertFileToByteArray("D:\\Images\\Image02.png"); using (Image pngimg = ConvertByteArrayToImage(pngba)) { SaveImageToFileSystem(pngimg, "D:\\Images\\Image02_Copy.png"); } byte[] gifba = ConvertFileToByteArray("D:\\Images\\Image03.gif"); using (Image gifimg = ConvertByteArrayToImage(gifba)) { SaveImageToFileSystem(gifimg, "D:\\Images\\Image03_Copy.gif"); } MessageBox.Show("Test Complete"); this.Close(); } private static byte[] ConvertFileToByteArray(String FilePath) { return File.ReadAllBytes(FilePath); } private static Image ConvertByteArrayToImage(byte[] ImageByteArray) { using (MemoryStream ms = new MemoryStream(ImageByteArray)) { return Image.FromStream(ms); } } private static void SaveImageToFileSystem(Image ImageObject, string FilePath) { // ImageObject.Save(FilePath, ImageObject.RawFormat); // This method only works with .png files. // This method works with .jpg, .png and .gif // Need to copy image before saving. using (Image img = new Bitmap(ImageObject.Width, ImageObject.Height)) { using (Graphics tg = Graphics.FromImage(img)) { tg.DrawImage(ImageObject, 0, 0); } img.Save(FilePath, img.RawFormat); } return; } 
+1
source share
3 answers

What I see from a quick glance:

Streams should be wrapped using a template (...), in your case, if an exception occurs during processing, Dispose () will not be called.

 using (FileStream fs = new FileStream(FilePath, FileMode.Open)) { // Another small optimization, removed unnecessary variable byte[] iba = new byte[(int)fs.Length]; fs.Read(iba, 0, iba.Length); } 

You should catch only those exceptions that you expect. For example, in SerializeImage it will be an IOException. Catching all exceptions is a very bad practice.

 } catch (IOException ex) { 

The Image.FromStream method depends on the stream, so if you close the base stream and return the image, you can get unpredictable behavior (well, in most cases this will work, but sometimes an error occurs). Therefore, you need to create a copy of the image and return it.

 using (MemoryStream ms = new MemoryStream(ImageByteArray)) { using (Image img = Image.FromStream(ms)) { return new Bitmap(img); } } 

You do not have the tg graphic and the img object in the SaveImage method (but the remote ImageObject, see the next paragraph). In general, I don’t see the need for such logic, just call ImageObject.Save (..., ImageFormat.Png) if you want to preserve the quality of saving images.

In the same method (SaveImage), you are in the ImageObject parameter. In most cases, this is also bad practice; consider disposing of this image outside the working method using a template (...).

+3
source

Here is a bit more:

 private void RunTest() { // byte array that can be stored in DB byte[] iba; // image object to display in picturebox or used to save to file system. iba = ReadImage("D:\\Images\\Image01.jpg"); using (Image img = DeserializeImage(iba)) { SaveImage(img, "D:\\Images\\Image01_Copy.jpg"); } iba = ReadImage("D:\\Images\\Image02.png"); using (Image img1 = DeserializeImage(iba)) { SaveImage(img1, "D:\\Images\\Image02_Copy.png"); } iba = ReadImage("D:\\Images\\Image03.gif"); using (var img2 = DeserializeImage(iba)) { SaveImage(img2, "D:\\Images\\Image03_Copy.gif"); } MessageBox.Show("Test Complete"); } private static byte[] ReadImage(String filePath) { // This seems to be the easiest way to serialize an image file // however it would be good to take a image object as an argument // in this method. using (var fs = new FileStream(filePath, FileMode.Open)) { Int32 fslength = Convert.ToInt32(fs.Length); var iba = new byte[fslength]; fs.Read(iba, 0, fslength); return iba; } } private static Image DeserializeImage(byte[] imageByteArray) { using (var ms = new MemoryStream(imageByteArray)) { return Image.FromStream(ms); } } private static void SaveImage(Image imageObject, string filePath) { // I could only get this method to work for .png files. // imageObject.Save(filePath, imageObject.RawFormat); // This method works with .jpg, .png and .gif // Need to copy image before saving. using (Image img = new Bitmap(imageObject.Width, imageObject.Height)) { using (Graphics tg = Graphics.FromImage(img)) { tg.DrawImage(imageObject, 0, 0); } img.Save(filePath, img.RawFormat); } return; } 

Pay attention to what you called Serialization - it's just reading bytes. Serialization is more than what you do when you save.

I got rid of all try / catch blocks. The best they have done for you is telling you if the problem was reading, saving, or deserializing. You can determine this from the stack trace that you destroyed only by displaying ex.Message.

You also returned null for a serious exception, propagating the failure.

In addition, I agree with everything that the arbitrator said.

+1
source

As John Sander says, serialization and deserialization is more than just reading raw data from a file. See the Wiki on Serialization

For images in .net you do not need to use anything more than the provided infrastructure methods (most of the time)

So there is image loading (de-serialization) in .net.

 using System.Drawing.Image; Image test; test = Image.FromFile(@"C:\myfile.jpg") test = Image.FromStream(myStream); // or you can load from an existing stream 

Similarly, image saving (serialization):

 test.Save(@"C:\anotherFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 

These are the basics of uploading and saving images in .net. If you have a more specific scenario, ask another question.

0
source

Source: https://habr.com/ru/post/924856/


All Articles