Grab a handful...you know you want to!We've all seen folks who have trouble dealing with for-switch statements, exception handling, dates/times and so forth. As such, it should come as no surprise that people have at least as much trouble dealing with images.

In practice, there are only so many things you can do with an image. You can load it from a file or URL. You can calculate its size. You can stuff it into some buffer. You can even display it in a variety of ways. As long as you have a graphics library handy, one would think that these things would be fairly straightforward tasks.

One would think.

Thomas works on a system that extracts images from a PDF, uses a third-party product to process them, and them puts the processed images back into the original PDF.

Of the many tasks involved in this process, he encountered two that stuck out as particularly well-designed...

First is the complex task of determining the number of bytes in an image. While:

  return Imgbyte.Length;

...would make most people happy, the author of this ingenuity decided that a whole lot more was required:

private static int GetPhysicalFileSize(byte[] Imgbyte, string InputObject, string OutFolder) {
  int PhysicalFileSize = 0;
  try {
      ExtractImage(Imgbyte, "Photo_" + InputObject + ".jpg", OutFolder);
      var Outfile = OutFolder + "\\Photo_" + InputObject + ".jpg";
      if (File.Exists(Outfile)) {
         FileInfo fi2 = new FileInfo(Outfile);
         PhysicalFileSize = (int)fi2.Length;
      }
      if (File.Exists(Outfile)) {
         File.Delete(Outfile);
      }
  } catch (Exception ex) {
    Trace.WriteError(ex);
  }
  return PhysicalFileSize;
}

Of course, When this developer went to actually process the image, he went a little bit further off the deep end, and passed an image by ref, copied it into another bitmap, read it into a memory stream, saved it on disk, and then copied it into a byte array...

private static byte[] ProcessImage(Bitmap bm, int Imageid, out bool processResult) {
  byte[] bmpBytes = null;
  // [snip]
  EncoderParameters eps = new EncoderParameters(1);
  eps.Param[0] = new EncoderParameter(Encoder.Quality, Config.CompressionRatio);
  var jpegCodecInfo = GetEncoderInfo("image/jpeg");
  try {
      using (Bitmap bmp = new Bitmap(bm)) {
        using (MemoryStream ms = new MemoryStream()) {
          bmp.Save(ms, jpegCodecInfo, eps);
          if (Config.ImplementEnhancedImage) {
             bmp.Save(Config.TempImageProcessing + 
                      "\\Output from Perfect Clear_" + 
                      Imageid + ".jpg",
                      jpegCodecInfo, 
                      eps);
          }
          bmpBytes = ms.GetBuffer();
        }
      }
  } catch (Exception ex) {
    processResult = false;
  }
  return bmpBytes;
}
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!