Search code examples
c#visual-studio-2008jpegcompact-frameworkwindows-ce

How to set PictureBox.Image to *.jpg-File on Compact Framework?


I am trying to develop a photo slideshow on a panel pc with Windows CE. Each of the images I want to show in a PictureBox on my formular is of *.jpg-Type. Files are e.g. ~1MB big with a resolution of 2304x1728. When I use following code, I get an OutOfMemory Exception.

Bitmap bitmap = new Bitmap(file_name)
PictureBox.Image = bitmap

After researching I found out that the *.jpg-Files might be "too big" to fit into Bitmap. With Compact Framework on VS2008 it is not possible for me to use something like

Image image1 = Image.From(file_name)

How can I get an image from jpg-Files to my PictureBox ?

EDIT[1]:

Thanks for your comments. I figured out that my pictures can not be loaded correctly because my device does not have enough memory to temporary load "huge" images. I solved the issue by writing some code that resizes my images before I copy them to my device.

        Image bitmapNew = null;
        using (Bitmap bitmap = (Bitmap)Image.FromFile(filename))
        {
            double proportion = (double) bitmap.Width / bitmap.Height;
            proportion = Math.Round(proportion, 2);
            if (proportion > 1)
            {
               iWidth = iWidthMax;
               iHeight = (int)(iWidthMax / proportion);
            }
            else
            {
               iHeight = iHeightMax;
               iWidth = (int) (iHeightMax * proportion);
            }
            bitmapNew = new Bitmap(bitmap, new Size(iWidth, iHeight));

       }

The device´s resolution defines the parameter iWidthMax & iHeightMax


Solution

  • The file size of a JPG or any other compressed image file type does not say how many pixels are stored (5, 10 or more megapixel). To show an image on screen, all pixels have to be loaded into memory. For larger images this is impossible, especially on Windows Mobile with it's 32MB process slot limitation. And even if the whole image could be loaded it would not make sense, as the screen does not have that number of pixels and would just show only every 10th or 20th pixel.

    The best approach is the load only what the screen and the memory can handle. The standard classes all are memory based and so you will reach the memory limit very early. But there is OpenNetCF which is able to 'scale' images on the fly using the file stream only.

    I used that in https://github.com/hjgode/eMdiMail/blob/master/ImagePanel/ImageHelper.cs to get scaled images that make sense to load and show. Look at the code for getScaledBitmap() and CreateThumbnail(). These functions are part of a custom control in the code but can easily be used for other purposes.

    The project was used to scan documents or business cards, show them as thumbs and zoomed and then eMail the scanned images to a document server.