(Read to the tune of "The Way We Were")

Bitmaps
Clog the corners of my RAM
Giant, duplicated bitmaps
of the memes that were

People say you can't have too much of a good thing. But for some things, even two of the same thing is one too many.

Such is the case with bitmaps. Well, not bitmaps, per se. Bitmaps are awesome. Bitmaps of memes involving the most interesting man in the world and some completely unrelated slogan. Bitmaps of fist pumping babies. Infogram bitmaps containing the insightful witticisms of Justin Bieber (admittedly, a small bitmap...but still). Everywhere you look, Bitmap awesomeness abounds.

But in-memory copies of bitmaps are a different story. Consider the following code, which is used to push a JPG image into the output stream of an HTTP response.


public void ResponseImageToBrowser(string fileName) 
{ 
	//convert image to byte array
	byte[] objImgData = ConvertImageToByteArray(new Bitmap(fileName), ImageFormat.Jpeg);
	MemoryStream objMemoryStream = new MemoryStream();
	objMemoryStream.Write(objImgData, 0, objImgData.Length);
	Image objImage = Image.FromStream(objMemoryStream);
	HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=" + fileName);
	HttpContext.Current.Response.ContentType = "image/Jpeg";
	objImage.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Jpeg);
	
	//close the file stream
	objMemoryStream.Close();
	objMemoryStream.Dispose();
	objImage.Dispose();
}

private byte[] ConvertImageToByteArray(Image objImageToConvert, ImageFormat objFormatOfImage) 
{
	byte[] objByteImage;
	using (MemoryStream objMemoryStream = new MemoryStream())
	{
		objImageToConvert.Save(objMemoryStream, objFormatOfImage);
		objByteImage = objMemoryStream.ToArray();
	}
	return objByteImage
}

Let's follow along.

First, the image is loaded into memory through the Bitmap class constructor. Then the bitmap class is saved into a memory stream (copy 2). This stream is converted into an array of bytes (copy 3).

Next, the byte array is written into a memory stream (copy 4) which is then loaded into an Image object (copy 5). Next, the Image object is saved into the output stream for the HTTP response (ostensibly, copy 6).

So in a mere 12 lines of code, a total of 6 copies of the images were placed into memory. Not sure if this qualifies, but Guinness has been notified just in case.

To rub salt into the wound, the above code could be replaced by two lines.


HttpContext.Current.Response.ContentType = "image/jpeg";
HttpContext.Current.Response.WriteFile(filename);

And finally, as a coup de grĂ¢ce, notice how even the comments duplicate the method names. After all, if you're going to double down (or sextuple down), don't be afraid to go all in.