Ejemplo n.º 1
0
        public Base64Image(string dataURI, FREE_IMAGE_LOAD_FLAGS flags)
        {
            Match match = Regex.Match(dataURI, @"data:image/(?<type>.+?);base64,(?<data>.+)");

            if (match.Groups["data"] != null)
            {
                byte[] byteArray = Convert.FromBase64String(match.Groups["data"].Value);
                using (MemoryStream byteStream = new MemoryStream(byteArray))
                {
                    dib.SetNull();
                    FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_PNG;
                    if (match.Groups["type"] != null)
                    {
                        switch (match.Groups["type"].Value.ToLower())
                        {
                        case "bmp":
                        {
                            format = FREE_IMAGE_FORMAT.FIF_BMP;
                            break;
                        }

                        case "png":
                        {
                            format = FREE_IMAGE_FORMAT.FIF_PNG;
                            break;
                        }

                        case "jpeg":
                        case "jpg":
                        {
                            format = FREE_IMAGE_FORMAT.FIF_JPEG;
                            break;
                        }

                        case "tga":
                        {
                            format = FREE_IMAGE_FORMAT.FIF_TARGA;
                            break;
                        }
                        }
                    }
                    dib = FreeImage.LoadFromStream(byteStream, flags, ref format);
                }
            }
        }
Ejemplo n.º 2
0
        public void Example01()
        {
            if (!File.Exists(fileName))
            {
                Console.WriteLine(fileName + " does not exist. Aborting.");
                return;
            }

            // Try to unload the bitmap handle (in case it is not null).
            // Always assert that a handle (like dib) is unloaded before it is reused, because
            // on unmanaged side there is no garbage collector that will clean up unreferenced
            // objects.
            // The following code will produce a memory leak (in case the bitmap is loaded
            // successfully) because the handle to the first bitmap is lost:
            //   dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
            //   dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
            if (!dib.IsNull)
            {
                FreeImage.Unload(dib);
            }

            // Loading a sample bitmap. In this case it's a .jpg file. 'Load' requires the file
            // format or the loading process will fail. An additional flag (the default value is
            // 'DEFAULT') can be set to enable special loading options.
            dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);

            // Check if the handle is null which means the bitmap could not be loaded.
            if (dib.IsNull)
            {
                Console.WriteLine("Loading bitmap failed. Aborting.");
                // Check whether there was an error message.
                return;
            }

            // Try flipping the bitmap.
            if (!FreeImage.FlipHorizontal(dib))
            {
                Console.WriteLine("Unable to flip bitmap.");
                // Check whether there was an error message.
            }

            // Store the bitmap back to disk. Again the desired format is needed. In this case the format is 'TIFF'.
            // An output filename has to be chosen (which will be overwritten without a warning).
            // A flag can be provided to enable pluginfunctions (compression is this case).
            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TIFF, dib, outFileName, FREE_IMAGE_SAVE_FLAGS.TIFF_DEFLATE);

            // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed.
            if (!dib.IsNull)
            {
                FreeImage.Unload(dib);
            }

            // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
            dib.SetNull();
        }
Ejemplo n.º 3
0
        public void Example01()
        {
            if (!File.Exists(fileName))
            {
                Console.WriteLine(fileName + " does not exist. Aborting.");
                return;
            }

            // Try to unload the bitmap handle (in case it is not null).
            // Always assert that a handle (like dib) is unloaded before it is reused, because
            // on unmanaged side there is no garbage collector that will clean up unreferenced
            // objects.
            // The following code will produce a memory leak (in case the bitmap is loaded
            // successfully) because the handle to the first bitmap is lost:
            //   dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
            //   dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);
            if (!dib.IsNull)
                FreeImage.Unload(dib);

            // Loading a sample bitmap. In this case it's a .jpg file. 'Load' requires the file
            // format or the loading process will fail. An additional flag (the default value is
            // 'DEFAULT') can be set to enable special loading options.
            dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE);

            // Check if the handle is null which means the bitmap could not be loaded.
            if (dib.IsNull)
            {
                Console.WriteLine("Loading bitmap failed. Aborting.");
                // Check whether there was an error message.
                return;
            }

            // Try flipping the bitmap.
            if (!FreeImage.FlipHorizontal(dib))
            {
                Console.WriteLine("Unable to flip bitmap.");
                // Check whether there was an error message.
            }

            // Store the bitmap back to disk. Again the desired format is needed. In this case the format is 'TIFF'.
            // An output filename has to be chosen (which will be overwritten without a warning).
            // A flag can be provided to enable pluginfunctions (compression is this case).
            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TIFF, dib, outFileName, FREE_IMAGE_SAVE_FLAGS.TIFF_DEFLATE);

            // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed.
            if (!dib.IsNull)
                FreeImage.Unload(dib);

            // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
            dib.SetNull();
        }
Ejemplo n.º 4
0
        public void Save(FIBITMAP dib, string fileName)
        {
            // Store the bitmap back to disk
            // TARGA_SAVE_RLE = 2
            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TARGA, dib, fileName, FREE_IMAGE_SAVE_FLAGS.TARGA_SAVE_RLE);

            // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed.
            if (!dib.IsNull)
            {
                FreeImage.Unload(dib);
            }

            // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
            dib.SetNull();
        }
Ejemplo n.º 5
0
        public Bitmap[] LoadImages(string[] fileNames)
        {
            var      bitmaps = new Bitmap[fileNames.Length];
            FIBITMAP dib;

            int i = 0;

            foreach (var f in fileNames)
            {
                if (!File.Exists(f))
                {
                    throw new Exception(f + " does not exist. Aborting.");
                }

                // load image
                dib = new FIBITMAP();
                dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TARGA, f, FREE_IMAGE_LOAD_FLAGS.DEFAULT);

                if (dib.IsNull)
                {
                    throw new Exception("Loading bitmap failed. Aborting.");
                }

                // convert to bitmap
                bitmaps[i] = FreeImage.GetBitmap(dib);
                i++;

                // free resources
                if (!dib.IsNull)
                {
                    FreeImage.Unload(dib);
                }
                // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
                dib.SetNull();
            }


            return(bitmaps);
        }
Ejemplo n.º 6
0
        public static Response GetPageImage(Guid id, int page, int width, int height, IResponseFormatter response)
        {
            // Restrict access to the FreeImage library to one thread at a time.
            lock (lockThis)
            {
                int  max_width  = 0;
                int  max_height = 0;
                bool thumbnail  = !(width == -1 && height == -1);
                bool processed  = false;

                string filename = string.Format("{0}-p{1}-w{2}-h{3}.jpg", id, page, width, height);

                if (thumbnail)
                {
                    MemoryStream cachestream = ImageCache.Instance.LoadFromCache(filename, true);
                    // Cached thumbnails are assumed to be in the correct format and adhere to the size/format restrictions of the ipad.
                    if (cachestream != null)
                    {
                        return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg")));
                    }
                }
                else
                {
                    // Check if a processed (rescaled and/or progressive) image is cached.
                    string       processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
                    MemoryStream cachestream        = ImageCache.Instance.LoadFromCache(processed_filename, false);
                    if (cachestream != null)
                    {
                        return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg")));
                    }
                }

                MemoryStream stream = null;

                // Check if original image is in the cache.
                string org_filename = string.Format("{0}-p{1}.jpg", id, page);
                stream = ImageCache.Instance.LoadFromCache(org_filename, false);

                if (stream == null)
                {
                    // Image is not in the cache, get it via ComicRack.
                    var bytes = GetPageImageBytes(id, page);
                    if (bytes == null)
                    {
                        return(HttpStatusCode.NotFound);
                    }

                    stream = new MemoryStream(bytes);

                    // Always save the original page to the cache
                    ImageCache.Instance.SaveToCache(org_filename, stream, false);
                }

                stream.Seek(0, SeekOrigin.Begin);

            #if USE_GDI
                Bitmap bitmap        = new Bitmap(stream, false);
                int    bitmap_width  = (int)bitmap.Width;
                int    bitmap_height = (int)bitmap.Height;
            #elif USE_DIB
                FIBITMAP dib = FreeImage.LoadFromStream(stream);
                if (dib == null)
                {
                    Console.WriteLine("Loading bitmap failed. Aborting.");
                    // Check whether there was an error message.
                    return(HttpStatusCode.InternalServerError);
                }
                int bitmap_width  = (int)FreeImage.GetWidth(dib);
                int bitmap_height = (int)FreeImage.GetHeight(dib);
            #elif USE_FIB
                FreeImageBitmap fib = FreeImageBitmap.FromStream(stream, false);
                if (fib == null)
                {
                    Console.WriteLine("Loading bitmap failed. Aborting.");
                    // Check whether there was an error message.
                    return(HttpStatusCode.InternalServerError);
                }

                int bitmap_width  = (int)fib.Width;
                int bitmap_height = (int)fib.Height;
            #endif

                if (ImageCache.Instance.use_max_dimension)
                {
                    int mw, mh;

                    if (bitmap_width >= bitmap_height)
                    {
                        mw = ImageCache.Instance.max_dimension_long;
                        mh = ImageCache.Instance.max_dimension_short;
                    }
                    else
                    {
                        mw = ImageCache.Instance.max_dimension_short;
                        mh = ImageCache.Instance.max_dimension_long;
                    }

                    if (bitmap_width > mw || bitmap_height > mh)
                    {
                        double scaleW = (double)mw / (double)bitmap_width;
                        double scaleH = (double)mh / (double)bitmap_height;
                        double scale  = Math.Min(scaleW, scaleH);

                        max_width  = (int)Math.Floor(scale * bitmap_width);
                        max_height = (int)Math.Floor(scale * bitmap_height);
                    }
                    else
                    {
                        max_width  = bitmap_width;
                        max_height = bitmap_height;
                    }
                }
                else
                // Check if the image dimensions exceeds the maximum image dimensions
                if ((bitmap_width * bitmap_height) > ImageCache.Instance.maximum_imagesize)
                {
                    max_width  = (int)Math.Floor(Math.Sqrt((double)bitmap_width / (double)bitmap_height * (double)ImageCache.Instance.maximum_imagesize));
                    max_height = (int)Math.Floor((double)max_width * (double)bitmap_height / (double)bitmap_width);
                }
                else
                {
                    max_width  = bitmap_width;
                    max_height = bitmap_height;
                }

                // Calculate the dimensions of the returned image.
                int result_width  = width;
                int result_height = height;

                if (result_width == -1 && result_height == -1)
                {
                    result_width  = max_width;
                    result_height = max_height;
                }
                else
                {
                    if (result_width == -1)
                    {
                        result_height = Math.Min(max_height, result_height);
                        double ratio = (double)result_height / (double)max_height;
                        result_width = (int)Math.Floor(((double)max_width * ratio));
                    }
                    else
                    if (result_height == -1)
                    {
                        result_width = Math.Min(max_width, result_width);
                        double ratio = (double)result_width / (double)max_width;
                        result_height = (int)Math.Floor(((double)max_height * ratio));
                    }
                }

                // TODO: do this per requesting target device instead of using one global setting.

                // Resize ?
                if (result_width != bitmap_width || result_height != bitmap_height)
                {
                    processed = true;

              #if USE_DIB || USE_FIB
                    //FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_BICUBIC;
                    FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_LANCZOS3;

                #if USE_FIB
                    fib.Rescale(result_width, result_height, resizer);
                #else
                    FIBITMAP newdib = FreeImage.Rescale(dib, result_width, result_height, resizer);
                    if (!newdib.IsNull)
                    {
                        FreeImage.Unload(dib);
                        dib.SetNull();
                        dib = newdib;
                    }
                #endif
              #elif USE_GDI
                    Bitmap resizedBitmap = Resize(bitmap, result_width, result_height);
                    bitmap.Dispose();
                    bitmap        = resizedBitmap;
                    resizedBitmap = null;
              #endif
                }


                // Check if the image must be converted to progressive jpeg
                if (ImageCache.Instance.use_progressive_jpeg && (result_width * result_height) >= ImageCache.Instance.progressive_jpeg_size_threshold)
                {
                    processed = true;

                    // Convert image to progressive jpeg

                    // FreeImage source code reveals that lower 7 bits of the FREE_IMAGE_SAVE_FLAGS enum are used for low-level quality control.
                    FREE_IMAGE_SAVE_FLAGS quality = (FREE_IMAGE_SAVE_FLAGS)ImageCache.Instance.progressive_jpeg_quality;
                    FREE_IMAGE_SAVE_FLAGS flags   = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | quality;

              #if USE_DIB || USE_FIB
                    stream.Dispose();
                    stream = new MemoryStream();

                #if USE_FIB
                    fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    fib.Dispose();
                #else
                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
                #endif
              #else
                    FIBITMAP dib = FreeImage.CreateFromBitmap(bitmap);
                    bitmap.Dispose();
                    bitmap = null;
                    stream.Dispose();
                    stream = new MemoryStream();

                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
              #endif
                }
                else
                if (processed)
                {
                    // image was rescaled, make new stream with rescaled bitmap

              #if USE_DIB || USE_FIB
                    FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_OPTIMIZE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;

                    stream.Dispose();
                    stream = new MemoryStream();

                #if USE_FIB
                    fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    fib.Dispose();
                #else
                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
                #endif
              #else
                    stream = GetBytesFromImage(bitmap);
              #endif
                    // For now, images that were resized because they exceeded the maximum dimensions are not saved to the cache.
                }

            #if USE_DIB
                FreeImage.Unload(dib);
                dib.SetNull();
            #elif USE_FIB
                fib.Dispose();
            #elif USE_GDI
                if (bitmap != null)
                {
                    bitmap.Dispose();
                    bitmap = null;
                }
            #endif

                // Always save thumbnails to the cache
                if (thumbnail)
                {
                    ImageCache.Instance.SaveToCache(filename, stream, true);
                }
                else
                if (processed)
                {
                    // Store rescaled and/or progressive jpegs in the cache for now.
                    string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
                    ImageCache.Instance.SaveToCache(processed_filename, stream, false);
                }

                stream.Seek(0, SeekOrigin.Begin);
                return(response.FromStream(stream, MimeTypes.GetMimeType(".jpg")));
            }
        }
Ejemplo n.º 7
0
 public void FreeImage_Unload()
 {
     Assert.That(dib.IsNull);
     dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, iManager.baseDirectory + @"JPEG\Image.jpg", FREE_IMAGE_LOAD_FLAGS.DEFAULT);
     Assert.IsNotNull(dib);
     FreeImage.Unload(dib);
     dib.SetNull();
 }
Ejemplo n.º 8
0
        public void FreeImage_MultiBitmap()
        {
            FIBITMAP temp;
            FIMULTIBITMAP mdib = FreeImage.OpenMultiBitmap(
                FREE_IMAGE_FORMAT.FIF_TIFF,
                @"test.tif",
                true,
                false,
                true,
                FREE_IMAGE_LOAD_FLAGS.DEFAULT);
            Assert.AreNotEqual(0, mdib);
            Assert.AreEqual(0, FreeImage.GetPageCount(mdib));
            dib = FreeImage.Allocate(10, 10, 8, 0, 0, 0);
            FreeImage.AppendPage(mdib, dib);
            Assert.AreEqual(1, FreeImage.GetPageCount(mdib));
            FreeImage.AppendPage(mdib, dib);
            Assert.AreEqual(2, FreeImage.GetPageCount(mdib));
            FreeImage.AppendPage(mdib, dib);
            Assert.AreEqual(3, FreeImage.GetPageCount(mdib));
            FreeImage.CloseMultiBitmapEx(ref mdib);
            FreeImage.UnloadEx(ref dib);
            mdib.SetNull();
            mdib = FreeImage.OpenMultiBitmap(FREE_IMAGE_FORMAT.FIF_TIFF, @"test.tif", false, false, true, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
            Assert.AreNotEqual(0, mdib);
            Assert.AreEqual(3, FreeImage.GetPageCount(mdib));
            dib = FreeImage.LockPage(mdib, 1);
            temp = FreeImage.LockPage(mdib, 2);

            int[] pages = null;
            int count = 0;
            FreeImage.GetLockedPageNumbers(mdib, pages, ref count);
            Assert.AreEqual(2, count);
            pages = new int[count];
            FreeImage.GetLockedPageNumbers(mdib, pages, ref count);
            Assert.AreEqual(2, pages.Length);
            FreeImage.UnlockPage(mdib, dib, false);
            FreeImage.UnlockPage(mdib, temp, true);
            dib.SetNull();
            Assert.IsTrue(FreeImage.MovePage(mdib, 0, 1));
            FreeImage.CloseMultiBitmapEx(ref mdib);
            Assert.IsTrue(System.IO.File.Exists("test.tif"));
            System.IO.File.Delete("test.tif");
        }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Загрузка изображения по полному пути
            /// </summary>
            /// <param name="file_name">Имя файла</param>
            //---------------------------------------------------------------------------------------------------------
            public void Load(String file_name)
            {
                if (!mFreeImageBitmap.IsNull)
                {
                    mFreeImageBitmap.SetNull();
                }

                // Try loading the file
                mFreeImageFormat = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
                mFreeImageBitmap = FreeImage.LoadEx(file_name, ref mFreeImageFormat);

                try
                {
                    // Error handling
                    if (mFreeImageBitmap.IsNull)
                    {
                        // Chech whether FreeImage generated an error messe
                        if (mCurrentMessage != null)
                        {
                            XLogger.LogErrorFormatModule(MODULE_NAME, "File could not be loaded!\nError:{0}", mCurrentMessage);
                        }
                        else
                        {
                            XLogger.LogErrorModule(MODULE_NAME, "File could not be loaded!");
                        }
                        return;
                    }


                    mFileName = file_name;

                    //
                    // РАЗМЕР ИЗОБРАЖЕНИЯ
                    //

                    // Read width
                    textWidth.Text = String.Format("Width: {0}", FreeImage.GetWidth(mFreeImageBitmap));

                    // Read height
                    textHeight.Text = String.Format("Height: {0}", FreeImage.GetHeight(mFreeImageBitmap));

                    // Read x-axis dpi
                    textDPI.Text = String.Format("DPI: x={0}, y={1}", FreeImage.GetResolutionX(mFreeImageBitmap),
                                                 FreeImage.GetResolutionY(mFreeImageBitmap));

                    //
                    // ПАРАМЕТРЫ ИЗОБРАЖЕНИЯ
                    //

                    // Read file format
                    textFileFormat.Text = String.Format("File Format: {0}", mFreeImageFormat);

                    // Read image type (FI_BITMAP, FIT_RGB16, FIT_COMPLEX ect)
                    textImageType.Text = String.Format("Image Type: {0}", FreeImage.GetImageType(mFreeImageBitmap));

                    // Read color type
                    textColorType.Text = String.Format("Color Depth: {0}", FreeImage.GetColorType(mFreeImageBitmap));

                    //
                    // ПАРАМЕТРЫ ЦВЕТА
                    //

                    // Read file format
                    textColorDepth.Text = String.Format("ColorDepth: {0}", FreeImage.GetBPP(mFreeImageBitmap));

                    // Read file format
                    textPixelFormat.Text = String.Format("PixelFormat: {0}", FreeImage.GetPixelFormat(mFreeImageBitmap));

                    // Read file format
                    textIsTransparent.Text = String.Format("IsTransparent: {0}", FreeImage.IsTransparent(mFreeImageBitmap));

                    //
                    // ПАРАМЕТРЫ МАСКИ
                    //

                    // Read red bitmask (16 - 32 bpp)
                    textRedMask.Text = String.Format("Red Mask: 0x{0:X8}", FreeImage.GetRedMask(mFreeImageBitmap));

                    // Read green bitmask (16 - 32 bpp)
                    textBlueMask.Text = String.Format("Green Mask: 0x{0:X8}", FreeImage.GetGreenMask(mFreeImageBitmap));

                    // Read blue bitmask (16 - 32 bpp)
                    textGreenMask.Text = String.Format("Blue Mask: 0x{0:X8}", FreeImage.GetBlueMask(mFreeImageBitmap));

                    // Получаем презентатор
                    if (mImagePresentator == null)
                    {
                        mImagePresentator = contentViewer.Content as Image;
                    }

                    // Основной режим
                    //mBitmapOriginal = FreeImage.GetBitmap(mFreeImageBitmap).ToBitmapSource();
                    mBitmapOriginal = null;                     // CreateFromHBitmap(FreeImage.GetHbitmap(mFreeImageBitmap, IntPtr.Zero, false));

                    // Если есть прозрачность
                    if (FreeImage.IsTransparent(mFreeImageBitmap) && FreeImage.GetBPP(mFreeImageBitmap) > 24)
                    {
                        // Получаем альфа-канал
                        FIBITMAP bitmap_alpha = FreeImage.GetChannel(mFreeImageBitmap, FREE_IMAGE_COLOR_CHANNEL.FICC_ALPHA);
                        if (!bitmap_alpha.IsNull)
                        {
                            mBitmapAlpha = null;                             // CreateFromHBitmap(FreeImage.GetHbitmap(bitmap_alpha, IntPtr.Zero, false));
                            FreeImage.UnloadEx(ref bitmap_alpha);
                        }

                        // Преобразуем
                        FIBITMAP bitmap_no_transparent = FreeImage.ConvertTo24Bits(mFreeImageBitmap);
                        if (!bitmap_no_transparent.IsNull)
                        {
                            mBitmapNoTransparent = null;                             // CreateFromHBitmap(FreeImage.GetHbitmap(bitmap_no_transparent, IntPtr.Zero, false));
                            FreeImage.UnloadEx(ref bitmap_no_transparent);
                        }

                        radioChannelAlpha.IsEnabled         = true;
                        radioChannelNoTransparent.IsEnabled = true;
                        if (radioChannelOriginal.IsChecked.Value)
                        {
                            mImagePresentator.Source = mBitmapOriginal;
                        }
                        else
                        {
                            radioChannelOriginal.IsChecked = true;
                        }
                    }
                    else
                    {
                        radioChannelAlpha.IsEnabled         = false;
                        radioChannelNoTransparent.IsEnabled = false;
                        if (radioChannelOriginal.IsChecked.Value)
                        {
                            mImagePresentator.Source = mBitmapOriginal;
                        }
                        else
                        {
                            radioChannelOriginal.IsChecked = true;
                        }
                    }

                    mImagePresentator.Width  = FreeImage.GetWidth(mFreeImageBitmap);
                    mImagePresentator.Height = FreeImage.GetHeight(mFreeImageBitmap);

                    if (mImagePresentator.Width > contentViewer.ViewportWidth - 30)
                    {
                        contentViewer.ContentScale = (contentViewer.ViewportWidth - 30) / mImagePresentator.Width;
                    }
                    else
                    {
                        contentViewer.ContentScale = 1.0;
                    }
                }
                catch (Exception exc)
                {
                    XLogger.LogExceptionModule(MODULE_NAME, exc);
                }

                // Always unload bitmap
                FreeImage.UnloadEx(ref mFreeImageBitmap);
            }
Ejemplo n.º 10
0
        public void Save(FIBITMAP dib, string fileName)
        {
            // Store the bitmap back to disk
            // TARGA_SAVE_RLE = 2
            FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TARGA, dib, fileName, FREE_IMAGE_SAVE_FLAGS.TARGA_SAVE_RLE);

            // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed.
            if (!dib.IsNull)
                FreeImage.Unload(dib);

            // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
            dib.SetNull();
        }
Ejemplo n.º 11
0
        public Bitmap[] LoadImages(string[] fileNames)
        {
            var bitmaps = new Bitmap[fileNames.Length];
            FIBITMAP dib;

            int i = 0;
            foreach (var f in fileNames)
            {
                if (!File.Exists(f))
                {
                    throw new Exception(f + " does not exist. Aborting.");
                }

                // load image
                dib = new FIBITMAP();
                dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TARGA, f, FREE_IMAGE_LOAD_FLAGS.DEFAULT);

                if (dib.IsNull)
                {
                    throw new Exception("Loading bitmap failed. Aborting.");
                }

                // convert to bitmap
                bitmaps[i] = FreeImage.GetBitmap(dib);
                i++;

                // free resources
                if (!dib.IsNull)
                    FreeImage.Unload(dib);
                // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap.
                dib.SetNull();
            }

            return bitmaps;
        }
Ejemplo n.º 12
0
        FIBITMAP LoadImageFromCache(string tileType, GMapTile g)
        {
            FIBITMAP image = new FIBITMAP();
            image.SetNull();

            while (image.IsNull)
            {
                bool useProxy;
                string src_filename = td.BuildFileName(tileType, g);
                if (src_filename != null && src_filename.Length > 0)
                {
                    string url = td.BuildURL(tileType, g, out useProxy);
                    // using temp file if tiles_per_file != 1
                    if (Properties.Settings.Default.MGMapsTilesPerFile == 1)
                    {
                        if (!td.IsCached(src_filename, g))
                            td.DownloadImage(url, src_filename, useProxy);
                    }
                    else
                    {
                        // FIX check if the image exists
                        String tempfile = Path.GetTempFileName();
            #if DEBUG
                        Console.WriteLine("Temp file: " + tempfile);
            #endif
                        try
                        {
                            if (!td.IsCached(src_filename, g))
                            {
                                td.DownloadImage(url, tempfile, useProxy);
            #if DEBUG
                                Console.WriteLine("Downloaded image from {0}", url);
            #endif
                                td.SaveImage(tempfile, src_filename, g);
                            }
                        }
                        finally
                        {
                            try
                            {
                                File.Delete(tempfile);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }

                if (worker.CancellationPending || Properties.Settings.Default.MGMapsTilesPerFile != 1)
                {
                    break;
                }

                //gkl changes - added synchronization based upon filename
                bool createdNew = false;
                Mutex synchobj = new Mutex(true, Regex.Replace(src_filename, "\\\\", "_"), out createdNew);
                if (synchobj != null)
                {
                    try
                    {
                        if (!createdNew)
                            synchobj.WaitOne();
                        if (!File.Exists(src_filename))
                        {
                            //blank image white
                            image = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 24, 0, 0, 0);
                            if (image.IsNull)
                            {
                                throw new InvalidOperationException(Properties.Resources.ExceptionCannotBuildBlankImage);
                            }
                            if (!FreeImage.Invert(image))
                            {
                                throw new InvalidOperationException(Properties.Resources.ExceptionCannotBuildBlankImage);
                            }
                            if (Properties.Settings.Default.SaveBlankImageForMissingTiles)
                            {
                                if (tileType == "GoogleSat" || tileType == "GoogleSatH" ||
                                    tileType == "GoogleTer" || tileType == "YahooMap" ||
                                     tileType == "YahooInMap" || tileType == "YahooSat" ||
                                     tileType == "YahooSatH" || tileType == "YahooSatH2" ||
                                     tileType == "MicrosoftSat" || tileType == "OpenAerialMap" ||
                                    tileType == "BrutMapSat" || tileType == "BrutMapSatH" ||
                                    tileType == "BrutMapAndNavSat" || tileType == "BrutMapAndNavSatH")
                                {
                                    if (!FreeImage.Save(
                                        FREE_IMAGE_FORMAT.FIF_JPEG,
                                        image, src_filename,
                                        FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB))
                                    {
                                        throw new InvalidOperationException(Properties.Resources.ExceptionCannotBuildBlankImage);
                                    }
                                }

                                else
                                {
                                    if (!FreeImage.Save(
                                        FREE_IMAGE_FORMAT.FIF_PNG,
                                        image, src_filename,
                                        FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION))
                                    {
                                        throw new InvalidOperationException(Properties.Resources.ExceptionCannotBuildBlankImage);
                                    }
                                }
                            }
                        }
                        else
                        {
                            image = FreeImage.Load(FreeImage.GetFileType(src_filename, 0), src_filename, 0);
                            if (image.IsNull)
                            {
                                File.Delete(src_filename);
                                if (Properties.Settings.Default.HaltOnImageFileCorrupted)
                                {
                                    throw new InvalidOperationException(String.Format(Properties.Resources.ExceptionLoadingImage, src_filename));
                                }
                            }
                        }
                    }
                finally //always release mutex
                    {
                        //gkl changes - added synchronization based upon filename
                            synchobj.ReleaseMutex();
                            synchobj.Close();
                    }
                }
            }

            return image;
        }
Ejemplo n.º 13
0
        public void BuildBigImage(string filename, ProgressWindow pw)
        {
            //FreeImage.SetOutputMessage(FreeImage_OutputMessageFunction);

            int topleftx, toplefty, bottomrightx, bottomrighty;
            uint topleftzoom, bottomrightzoom;

            GMapTile.XYZoom(topleft, out topleftx, out toplefty, out topleftzoom);
            GMapTile.XYZoom(bottomright, out bottomrightx, out bottomrighty, out bottomrightzoom);

            //gkl changes - passed in new delegate
            td = new TileDownloader(outsidereportFunction, worker);

            FIBITMAP bigImage = new FIBITMAP(), image = new FIBITMAP();

            try
            {
                imageWidth = (bottomrightx - topleftx + 1) * GMapTile.TILE_SIZE;
                imageHeight = (bottomrighty - toplefty + 1) * GMapTile.TILE_SIZE;

                if (imageFormat != FREE_IMAGE_FORMAT.FIF_UNKNOWN)
                {
                    reportFunction("Allocating memory for image", 0);

                    if ((imageWidth > 65535) || (imageHeight > 65535))
                    {
                        throw new InvalidOperationException(Properties.Resources.ExceptionImageMemoryAllocation);
                    }
                    bigImage = FreeImage.Allocate(imageWidth, imageHeight, grayscale ? 8 : 24, 0, 0, 0);
                    if (bigImage.IsNull)
                    {
                        throw new InvalidOperationException(Properties.Resources.ExceptionImageMemoryAllocation);
                    }
                }

                int wholeQuant = (bottomrightx - topleftx + 1) * (bottomrighty - toplefty + 1);
                bool paletteInit = false;

                for (int yy = toplefty; yy <= bottomrighty; yy++)
                {
                    for (int xx = topleftx; xx <= bottomrightx; xx++)
                    {
                        if (worker.CancellationPending)
                        {
                            return;
                        }

                        try
                        {
                            GMapTile g = new GMapTile(xx, yy, topleftzoom);

                            while (pw.paused)
                            {
                                reportFunction("< Paused >", 0);
                                Thread.Sleep(1000);
                            }

                            if (pw.allCancelled)
                            {
                                reportFunction("< Cancelled >", 0);
                                return;
                            }

                            if (Properties.Settings.Default.OperatingMode == 3 || Properties.Settings.Default.OperatingMode == 4 || Properties.Settings.Default.OperatingMode == 5 || Properties.Settings.Default.OperatingMode == 6)
                                reportFunction("(Down)loading image (" + xx + "," + yy + ")", 0);
                            else
                                reportFunction("(Down)loading image " + g.Quadtree, ((!grayscale && dither8bpp ? 0.0 : 50.0) + 100.0) / (double)wholeQuant);

                            FIBITMAP image_alpha;
                            FIBITMAP image_alpha2;
                            FIBITMAP image_result;

                            switch (tileTypeInt)
                            {
                                case 0: //map only
                                    image = LoadImageFromCache("GoogleMap", g);
                                    break;
                                case 1: //satellite only
                                    image = LoadImageFromCache("GoogleSat", g);
                                    break;
                                case 2: //hybrid
                                    image = LoadImageFromCache("GoogleSatH", g);

                                    if (worker.CancellationPending)
                                    {
                                        return;
                                    }

                                    image_alpha = LoadImageFromCache("GoogleHyb", g);

                                    if (FreeImage.GetBPP(image_alpha) != 32)
                                    {
                                        //sometimes alpha tile from GG is a 2bits image, it means tile is blank
                                        break;
                                    }

                                    if (Properties.Settings.Default.DrivingMapTransparency != 100)
                                    {
                                        image_alpha2 = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 32, 0, 0, 0);
                                        if (!FreeImage.Paste(image_alpha2, image_alpha, 0, 0, ((int)Properties.Settings.Default.DrivingMapTransparency * 256) / 100))
                                        {
                                            //sometimes alpha tile from GG is corrupted, it means tile is blank
                                            //we keep tile
                                        }
                                        FreeImage.Unload(image_alpha);
                                        image_alpha = image_alpha2;
                                    }

                                    image_result = FreeImage.Composite(image_alpha, false, null, image);
                                    FreeImage.Unload(image_alpha);
                                    if (!image_result.IsNull)
                                    {
                                        FreeImage.Unload(image);
                                        image = image_result;
                                    }
                                    else
                                    {
                                        //sometimes alpha tile from GG is corrupted, it means tile is blank
                                        //we keep image
                                    }
                                    break;
                                case 3:
                                    image = LoadImageFromCache("GoogleTer", g);
                                    break;
                                case 4:
                                    image = LoadImageFromCache("GoogleChina", g);
                                    break;
                                case 5:
                                    image = LoadImageFromCache("MicrosoftMap", g);
                                    break;
                                case 6:
                                    image = LoadImageFromCache("MicrosoftSat", g);
                                    break;
                                case 7:
                                    image = LoadImageFromCache("MicrosoftHyb", g);
                                    break;
                                case 8:
                                    image = LoadImageFromCache("MicrosoftTer", g);
                                    break;
                                case 9:
                                    image = LoadImageFromCache("MicrosoftBrMap", g);
                                    break;
                                case 10:
                                    image = LoadImageFromCache("YahooMap", g);
                                    break;
                                case 11:
                                    image = LoadImageFromCache("YahooSat", g);
                                    break;
                                case 12:
                                    image = LoadImageFromCache("YahooSatH", g);

                                    if (worker.CancellationPending)
                                    {
                                        return;
                                    }

                                    image_alpha = LoadImageFromCache("YahooHyb", g);

                                    if (FreeImage.GetBPP(image_alpha) != 32)
                                    {
                                        //sometimes alpha tile from GG is a 2bits image, it means tile is blank
                                        break;
                                    }

                                    if (Properties.Settings.Default.DrivingMapTransparency != 100)
                                    {
                                        image_alpha2 = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 32, 0, 0, 0);
                                        if (!FreeImage.Paste(image_alpha2, image_alpha, 0, 0, ((int)Properties.Settings.Default.DrivingMapTransparency * 256) / 100))
                                        {
                                            //sometimes alpha tile from GG is corrupted, it means tile is blank
                                            //we keep tile
                                        }
                                        FreeImage.Unload(image_alpha);
                                        image_alpha = image_alpha2;
                                    }

                                    image_result = FreeImage.Composite(image_alpha, false, null, image);
                                    FreeImage.Unload(image_alpha);
                                    if (!image_result.IsNull)
                                    {
                                        FreeImage.Unload(image);
                                        image = image_result;
                                    }
                                    else
                                    {
                                        //sometimes alpha tile from GG is corrupted, it means tile is blank
                                        //we keep image
                                    }
                                    break;
                                case 13:
                                    image = LoadImageFromCache("YahooInMap", g);
                                    break;
                                case 14:
                                    image = LoadImageFromCache("YahooSatH2", g);

                                    if (worker.CancellationPending)
                                    {
                                        return;
                                    }

                                    image_alpha = LoadImageFromCache("YahooInHyb", g);

                                    if (FreeImage.GetBPP(image_alpha) != 32)
                                    {
                                        //sometimes alpha tile from GG is a 2bits image, it means tile is blank
                                        break;
                                    }

                                    if (Properties.Settings.Default.DrivingMapTransparency != 100)
                                    {
                                        image_alpha2 = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 32, 0, 0, 0);
                                        if (!FreeImage.Paste(image_alpha2, image_alpha, 0, 0, ((int)Properties.Settings.Default.DrivingMapTransparency * 256) / 100))
                                        {
                                            //sometimes alpha tile from GG is corrupted, it means tile is blank
                                            //we keep tile
                                        }
                                        FreeImage.Unload(image_alpha);
                                        image_alpha = image_alpha2;
                                    }

                                    image_result = FreeImage.Composite(image_alpha, false, null, image);
                                    FreeImage.Unload(image_alpha);
                                    if (!image_result.IsNull)
                                    {
                                        FreeImage.Unload(image);
                                        image = image_result;
                                    }
                                    else
                                    {
                                        //sometimes alpha tile from GG is corrupted, it means tile is blank
                                        //we keep image
                                    }
                                    break;
                                case 15:
                                    image = LoadImageFromCache("OpenStreetMap", g);
                                    break;
                                case 16:
                                    image = LoadImageFromCache("OSMARender", g);
                                    break;
                                case 17:
                                    image = LoadImageFromCache("OpenAerialMap", g);
                                    break;
                                case 18:
                                    image = LoadImageFromCache("OpenCycleMap", g);
                                    break;
                                case 19:
                                    image = LoadImageFromCache("BrutMap", g);
                                    break;
                                case 20:
                                    image = LoadImageFromCache("BrutMapAndNav", g);
                                    break;
                                case 21:
                                    image = LoadImageFromCache("BrutMapSat", g);
                                    break;
                                case 22:
                                    image = LoadImageFromCache("BrutMapAndNavSat", g);
                                    break;
                                case 23: //hybrid
                                    image = LoadImageFromCache("BrutMapSatH", g);

                                    if (worker.CancellationPending)
                                    {
                                        return;
                                    }

                                    image_alpha = LoadImageFromCache("BrutMapHyb", g);

                                    if (FreeImage.GetBPP(image_alpha) < 8)
                                    {
                                        //sometimes alpha tile from GG is a 2bits image, it means tile is blank
                                        break;
                                    }

                                    if (Properties.Settings.Default.DrivingMapTransparency != 100)
                                    {
                                        image_alpha2 = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 32, 0, 0, 0);
                                        if (!FreeImage.Paste(image_alpha2, image_alpha, 0, 0, ((int)Properties.Settings.Default.DrivingMapTransparency * 256) / 100))
                                        {
                                            //sometimes alpha tile from GG is corrupted, it means tile is blank
                                            //we keep tile
                                        }
                                        FreeImage.Unload(image_alpha);
                                        image_alpha = image_alpha2;
                                    }

                                    image_result = FreeImage.Composite(image_alpha, false, null, image);
                                    FreeImage.Unload(image_alpha);
                                    if (!image_result.IsNull)
                                    {
                                        FreeImage.Unload(image);
                                        image = image_result;
                                    }
                                    else
                                    {
                                        //sometimes alpha tile from GG is corrupted, it means tile is blank
                                        //we keep image
                                    }
                                    string hyb_file = td.BuildFileName("BrutMapSH", g);
                                    if (!FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, image, hyb_file, 0))
                                    {
                                        throw new IOException(Properties.Resources.ExceptionCannotSaveFile);
                                    }
                                    break;
                                case 24: //hybrid
                                    image = LoadImageFromCache("BrutMapAndNavSatH", g);

                                    if (worker.CancellationPending)
                                    {
                                        return;
                                    }

                                    image_alpha = LoadImageFromCache("BrutMapAndNavHyb", g);

                                    if (FreeImage.GetBPP(image_alpha) < 8)
                                    {
                                        //sometimes alpha tile from GG is a 2bits image, it means tile is blank
                                        break;
                                    }

                                    if (Properties.Settings.Default.DrivingMapTransparency != 100)
                                    {
                                        image_alpha2 = FreeImage.Allocate(GMapTile.TILE_SIZE, GMapTile.TILE_SIZE, 32, 0, 0, 0);
                                        if (!FreeImage.Paste(image_alpha2, image_alpha, 0, 0, ((int)Properties.Settings.Default.DrivingMapTransparency * 256) / 100))
                                        {
                                            //sometimes alpha tile from GG is corrupted, it means tile is blank
                                            //we keep tile
                                        }
                                        FreeImage.Unload(image_alpha);
                                        image_alpha = image_alpha2;
                                    }

                                    image_result = FreeImage.Composite(image_alpha, false, null, image);
                                    FreeImage.Unload(image_alpha);
                                    if (!image_result.IsNull)
                                    {
                                        FreeImage.Unload(image);
                                        image = image_result;
                                    }
                                    else
                                    {
                                        //sometimes alpha tile from GG is corrupted, it means tile is blank
                                        //we keep image
                                    }
                                    string hyb_file_andnav = td.BuildFileName("BrutMapAndNavSH", g);
                                    if (!FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, image, hyb_file_andnav, 0))
                                    {
                                        throw new IOException(Properties.Resources.ExceptionCannotSaveFile);
                                    }
                                    break;
                            }

                            if (Properties.Settings.Default.OperatingMode == 3 || Properties.Settings.Default.OperatingMode == 4 || Properties.Settings.Default.OperatingMode == 5 || Properties.Settings.Default.OperatingMode == 6)
                                reportFunction("Image download completed (" + xx + "," + yy + ")", 100.0 / (double)wholeQuant);

                            if (worker.CancellationPending)
                            {
                                return;
                            }

                            if (imageFormat == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
                            {
                                continue;
                            }

                            if (grayscale)
                            {
                                //uint image2 = FreeImage.ConvertPalette(bigImage, image);
                                FIBITMAP image3 = FreeImage.ConvertTo24Bits(image);
                                if (image3.IsNull)
                                {
                                    throw new InvalidOperationException(Properties.Resources.ExceptionCannotConvert24bpp);
                                }
                                FIBITMAP image2 = FreeImage.ConvertTo8Bits(image3);
                                FreeImage.Unload(image3);
                                if (image2.IsNull)
                                {
                                    throw new InvalidOperationException(Properties.Resources.ExceptionCannotConvertGrayscale);
                                }
                                FreeImage.Unload(image);
                                image = image2;
                                /* FIXME
                                 * if (!paletteInit)
                                {
                                    if (!FreeImage.PaletteCopy(image, bigImage))
                                    {
                                        throw new InvalidOperationException(Properties.Resources.ExceptionGrayscalePalette);
                                    }
                                    paletteInit = true;
                                }
                                 */
                            }

                            reportFunction("Pasting " + g.Quadtree, 0);

                            if (!FreeImage.Paste(bigImage, image, (xx - topleftx) * GMapTile.TILE_SIZE, (yy - toplefty) * GMapTile.TILE_SIZE, 256))
                            {
                                throw new InvalidOperationException(Properties.Resources.ExceptionPastingImage);
                            }
                        }
                        catch (Exception)
                        {
                            if (Properties.Settings.Default.OperatingMode == 3 || Properties.Settings.Default.OperatingMode == 4 || Properties.Settings.Default.OperatingMode == 5 || Properties.Settings.Default.OperatingMode == 6)
                                reportFunction("Image download failed (" + xx + "," + yy + ")", 100.0 / (double)wholeQuant);
                        }
                        finally
                        {
                            FreeImage.Unload(image);
                            image.SetNull();
                        }
                    }
                }

                if (worker.CancellationPending || (imageFormat == FREE_IMAGE_FORMAT.FIF_UNKNOWN))
                {
                    return;
                }

                if (!grayscale && dither8bpp)
                {
                    reportFunction("Converting image to 8bpp", 0.0);
                    FIBITMAP bigImage8 = FreeImage.ColorQuantize(bigImage, FREE_IMAGE_QUANTIZE.FIQ_WUQUANT);
                    if (bigImage8.IsNull)
                    {
                        throw new InvalidOperationException(Properties.Resources.ExceptionConversion24bpp8bpp);
                    }
                    FreeImage.Unload(bigImage);
                    bigImage = bigImage8;
                    reportFunction("Image converted", 50.0);
                }

                if (worker.CancellationPending)
                {
                    return;
                }

                reportFunction("Saving image to " + Path.GetFileName(filename), 0.0);
                if (!FreeImage.Save(imageFormat, bigImage, filename, saveflags))
                {
                    throw new IOException(Properties.Resources.ExceptionCannotSaveFile);
                }

                reportFunction("Image saved", 50.0);
            }
            finally
            {
                FreeImage.Unload(bigImage);
            }
        }