Ejemplo n.º 1
0
        private void save(DibMd dibMd, string dstPath)
        {
            if (dibMd == null)
            {
                return;
            }

            string                dstSuffix = Path.GetExtension(dstPath).ToLower();
            FREE_IMAGE_FORMAT     format    = FREE_IMAGE_FORMAT.FIF_ICO;
            FREE_IMAGE_SAVE_FLAGS flag      = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE;

            switch (dstSuffix)
            {
            case ".png": format = FREE_IMAGE_FORMAT.FIF_PNG; flag = FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION; break;

            case ".jpg": format = FREE_IMAGE_FORMAT.FIF_JPEG; flag = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD; break;

            case ".bmp": format = FREE_IMAGE_FORMAT.FIF_BMP; flag = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE; break;

            case ".ico":
            default: break;
            }
            FreeImage.Save(format, dibMd.dib, dstPath, flag);
            //bool isOk = FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, dibOut, dstPath + ".png", FREE_IMAGE_SAVE_FLAGS.PNG_INTERLACED);
            //FreeImage.Unload(dibMd.dib);
            //FreeImage.Unload(dib);
        }
Ejemplo n.º 2
0
        private void saveToStream(DibMd dibMd, string dstSuffix, Stream stream)
        {
            if (dibMd == null)
            {
                return;
            }

            //string dstSuffix = Path.GetExtension(dstPath).ToLower();
            FREE_IMAGE_FORMAT     format = FREE_IMAGE_FORMAT.FIF_ICO;
            FREE_IMAGE_SAVE_FLAGS flag   = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE;

            switch (dstSuffix)
            {
            case ".png": format = FREE_IMAGE_FORMAT.FIF_PNG; flag = FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION; break;

            case ".jpg": format = FREE_IMAGE_FORMAT.FIF_JPEG; flag = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD; break;

            case ".bmp": format = FREE_IMAGE_FORMAT.FIF_BMP; flag = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE; break;

            case ".ico":
            default: break;
            }

            FreeImage.SaveToStream(dibMd.dib, stream, format, flag);
        }
Ejemplo n.º 3
0
        /**
         * Outputs displayable image of image channel to be corrected.
         * @param layer the channel corrected
         * @return true if successful
         **/
        private void outputDisplayableBase(int layer)
        {
            float[] array;
            int     width = base_dimensions[0];
            int     height = base_dimensions[1];
            float   value, value16bpp;

            string image_name = (string)dropdown_imageLayer.Items[layer];

            array = new float[width * height];
            Array.Copy(base_data, width * height * layer, array, 0, width * height);

            FREE_IMAGE_FORMAT     format     = FREE_IMAGE_FORMAT.FIF_TIFF;
            FREE_IMAGE_TYPE       type       = FREE_IMAGE_TYPE.FIT_FLOAT;
            FREE_IMAGE_SAVE_FLAGS save_flags = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE;
            FreeImageBitmap       image      = new FreeImageBitmap(width, height, type);

            float maxValue = Enumerable.Range(0, array.Length).Max(m => array[m]);
            float minValue = Enumerable.Range(0, array.Length).Min(m => array[m]);

            for (int j = 0; j < height; ++j)
            {
                Scanline <float> scanline = image.GetScanline <float>(j);
                for (int k = 0; k < width; ++k)
                {
                    value      = array[width * j + k];
                    value16bpp = (1.0f / (maxValue - minValue) * (value - minValue));
                    scanline.SetValue(value16bpp, k);
                }
            }
            image.RotateFlip(base_orientation);
            image.Save("./Workspace/" + image_name + "_base_displayable.tiff", format, save_flags);
        }
Ejemplo n.º 4
0
        /**
         * Outputs .tiff file to be read into Argo Solution as input parameter
         * @param layer the channel corrected
         * @return true if successful
         **/
        private bool outputBase(int layer)
        {
            float[] array;
            int     width  = base_dimensions[0];
            int     height = base_dimensions[1];
            float   value;

            if (layer == -1)
            {
                return(false);
            }

            string image_name = (string)dropdown_imageLayer.Items[layer];

            array = new float[width * height];
            Array.Copy(base_data, width * height * layer, array, 0, width * height);

            FREE_IMAGE_FORMAT     format     = FREE_IMAGE_FORMAT.FIF_TIFF;
            FREE_IMAGE_TYPE       type       = FREE_IMAGE_TYPE.FIT_FLOAT;
            FREE_IMAGE_SAVE_FLAGS save_flags = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE;
            FreeImageBitmap       image      = new FreeImageBitmap(width, height, type);

            for (int j = 0; j < height; ++j)
            {
                Scanline <float> scanline = image.GetScanline <float>(j);
                for (int k = 0; k < width; ++k)
                {
                    value = array[width * j + k];
                    scanline.SetValue(value, k);
                }
            }
            image.RotateFlip(base_orientation);
            image.Save("./Workspace/" + image_name + "_base.tiff", format, save_flags);
            return(true);
        }
Ejemplo n.º 5
0
        public FreeImageEncoderPlugin(ResizeSettings settings, object original)
        {
            ImageFormat originalFormat = DefaultEncoder.GetOriginalFormat(original);
            if (!IsValidOutputFormat(originalFormat)) originalFormat = ImageFormat.Jpeg;//No valid info available about the original format. Use Jpeg.

            //What format was specified?
            ImageFormat requestedFormat = DefaultEncoder.GetRequestedFormat(settings.Format, originalFormat); //fallback to originalFormat if not specified.
            if (!IsValidOutputFormat(requestedFormat))
                throw new ArgumentException("An unrecognized or unsupported output format (" + (settings.Format != null ? settings.Format : "(null)") + ") was specified in 'settings'.");
            this.format =  FreeImage.GetFormat(requestedFormat);

            //Parse JPEG settings.
            int quality = 90;
            if (string.IsNullOrEmpty(settings["quality"]) || !int.TryParse(settings["quality"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out quality)) quality = 90;
            if (format == FREE_IMAGE_FORMAT.FIF_JPEG) {
                if (quality >= 100) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                else if (quality >= 75)
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                else if (quality >= 50) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                else if (quality >= 25) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                else encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;

                if ("true".Equals(settings["progressive"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE;

                if ("411".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_411;
                if ("420".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420;
                if ("422".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_422;
                if ("444".Equals(settings["subsampling"])) encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;
            }
            if (string.IsNullOrEmpty(settings["colors"]) || !int.TryParse(settings["colors"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out colors)) colors = -1;

            if (format == FREE_IMAGE_FORMAT.FIF_GIF) {
                //encodingOptions = FREE_IMAGE_SAVE_FLAGS.
            }
        }
        public static void SavePng(Image img, Stream stream, FreeImagePngQuality freeImagePngQualityType, bool bInterlaced)
        {
            using (FreeImageAPI.FreeImageBitmap fib = new FreeImageAPI.FreeImageBitmap(img))
            {
                FREE_IMAGE_SAVE_FLAGS pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION;

                switch (freeImagePngQualityType)
                {
                case FreeImagePngQuality.PNG_Z_BEST_COMPRESSION:
                    pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_COMPRESSION;
                    break;

                case FreeImagePngQuality.PNG_Z_BEST_SPEED:
                    pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_SPEED;

                    break;

                case FreeImagePngQuality.PNG_Z_DEFAULT_COMPRESSION:
                    pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION;
                    break;

                case FreeImagePngQuality.PNG_Z_NO_COMPRESSION:
                    pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_Z_NO_COMPRESSION;
                    break;
                }

                if (bInterlaced)
                {
                    pngQuality = FREE_IMAGE_SAVE_FLAGS.PNG_INTERLACED | pngQuality;
                }

                fib.Save(stream, FreeImageAPI.FREE_IMAGE_FORMAT.FIF_PNG, pngQuality);
            }
        }
Ejemplo n.º 7
0
Archivo: Program.cs Proyecto: dotob/wop
 private static TimeSpan DoTest(FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS quality)
 {
     foreach (string s in Directory.GetFiles(@"..\..\..\testdata\pix", "*small*")) {
     //File.Delete(s);
       }
       DateTime start = DateTime.Now;
       foreach (string s in Directory.GetFiles(@"..\..\..\testdata\pix", "test*jpg")) {
     var fin = new FileInfo(s);
     var fout = new FileInfo(Path.Combine(fin.DirectoryName, string.Format("t{0}_small_{1}_{2}.jpg", fin.NameWithoutExtension(), filter, quality)));
     ImageWorker.ShrinkImageFI(fin, fout, new Size(400, 400), FREE_IMAGE_FORMAT.FIF_JPEG, filter, quality, true);
     Console.WriteLine("{0} -> {1}", fin.Name, fout.Name);
       }
       TimeSpan ts = DateTime.Now.Subtract(start);
       string d = Directory.GetCurrentDirectory();
       return ts;
 }
        public static void SaveTiff(Image img, Stream stream, FreeImageTiffQuality freeImageTiffQuality)
        {
            using (FreeImageAPI.FreeImageBitmap fib = new FreeImageAPI.FreeImageBitmap(img))
            {
                FREE_IMAGE_SAVE_FLAGS tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE;

                switch (freeImageTiffQuality)
                {
                case FreeImageTiffQuality.TIFF_ADOBE_DEFLATE:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_ADOBE_DEFLATE;
                    break;

                case FreeImageTiffQuality.TIFF_CCITTFAX3:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_CCITTFAX3;
                    break;

                case FreeImageTiffQuality.TIFF_CCITTFAX4:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_CCITTFAX4;
                    break;

                case FreeImageTiffQuality.TIFF_DEFLATE:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_DEFLATE;
                    break;

                case FreeImageTiffQuality.TIFF_JPEG:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_JPEG;
                    break;

                case FreeImageTiffQuality.TIFF_LZW:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_LZW;
                    break;

                case FreeImageTiffQuality.TIFF_NONE:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE;
                    break;

                case FreeImageTiffQuality.TIFF_PACKBITS:
                    tiffQuality = FREE_IMAGE_SAVE_FLAGS.TIFF_PACKBITS;
                    break;
                }

                fib.Save(stream, FreeImageAPI.FREE_IMAGE_FORMAT.FIF_TIFF, tiffQuality);
            }
        }
Ejemplo n.º 9
0
        private static TimeSpan DoTest(FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS quality)
        {
            foreach (string s in Directory.GetFiles(@"..\..\..\testdata\pix", "*small*"))
            {
                //File.Delete(s);
            }
            DateTime start = DateTime.Now;

            foreach (string s in Directory.GetFiles(@"..\..\..\testdata\pix", "test*jpg"))
            {
                var fin  = new FileInfo(s);
                var fout = new FileInfo(Path.Combine(fin.DirectoryName, string.Format("t{0}_small_{1}_{2}.jpg", fin.NameWithoutExtension(), filter, quality)));
                ImageWorker.ShrinkImageFI(fin, fout, new Size(400, 400), FREE_IMAGE_FORMAT.FIF_JPEG, filter, quality, true);
                Console.WriteLine("{0} -> {1}", fin.Name, fout.Name);
            }
            TimeSpan ts = DateTime.Now.Subtract(start);
            string   d  = Directory.GetCurrentDirectory();

            return(ts);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Closes a previously opened multi-page bitmap and, when the bitmap was not opened read-only,
 /// applies any changes made to it.
 /// On success the handle will be reset to null.
 /// </summary>
 /// <param name="dib">Handle to a FreeImage multi-paged bitmap.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 public static bool CloseMultiBitmapEx(ref FIMULTIBITMAP dib, FREE_IMAGE_SAVE_FLAGS flags)
 {
     bool result = false;
     if (!dib.IsNull)
     {
         if (CloseMultiBitmap(dib, flags))
         {
             dib = 0;
             result = true;
         }
     }
     return result;
 }
Ejemplo n.º 11
0
    public IEnumerator SaveTexture(string extension, Texture2D textureToSave, string pathToFile)
    {
        busy = true;

        if (textureToSave != null)
        {
            FREE_IMAGE_FORMAT     imageFormat = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
            FREE_IMAGE_SAVE_FLAGS flags       = FREE_IMAGE_SAVE_FLAGS.DEFAULT;

            bool useFIF = true;

            switch (extension.ToLower())
            {
            case "bmp":
                imageFormat = FREE_IMAGE_FORMAT.FIF_BMP;
                break;

            case "tga":
                imageFormat = FREE_IMAGE_FORMAT.FIF_TARGA;
                break;

            case "tiff":
                imageFormat = FREE_IMAGE_FORMAT.FIF_TIFF;
                flags       = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE;
                break;

            case "png":
                byte[] pngBytes = textureToSave.EncodeToPNG();
                File.WriteAllBytes(pathToFile + ".png", pngBytes);
                useFIF = false;
                //imageFormat = FREE_IMAGE_FORMAT.FIF_PNG;
                break;

            case "jpg":
                byte[] jpgBytes = textureToSave.EncodeToJPG();
                File.WriteAllBytes(pathToFile + ".jpg", jpgBytes);
                useFIF = false;
                //imageFormat = FREE_IMAGE_FORMAT.FIF_JPEG;
                //flags = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                break;

            default:
                imageFormat = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
                break;
            }

            if (useFIF)
            {
                byte[] bytes = textureToSave.EncodeToPNG();

                string tempFilePath = Application.dataPath + pathChar + "temp.png";
                //string tempFilePath = Application.persistentDataPath + pathChar + "temp.png";
                File.WriteAllBytes(tempFilePath, bytes);

                FIBITMAP bitmap      = FreeImage_Load(FREE_IMAGE_FORMAT.FIF_PNG, tempFilePath, 0);
                bool     saveSuccess = FreeImage_Save(imageFormat, bitmap, pathToFile + "." + extension, flags);
                FreeImage_Unload(bitmap);

                //File.Delete (tempFilePath);
            }

            Resources.UnloadUnusedAssets();
        }
        yield return(new WaitForSeconds(0.01f));

        busy = false;
    }
 private static extern bool CloseMultiBitmap_(FIMULTIBITMAP bitmap, FREE_IMAGE_SAVE_FLAGS flags);
        public static extern bool SaveToHandle(FREE_IMAGE_FORMAT fif, FIBITMAP dib, ref FreeImageIO io, fi_handle handle,
			FREE_IMAGE_SAVE_FLAGS flags);
Ejemplo n.º 14
0
        public void extractPage(FreeImageBitmap image, int padding, Stream stream, PagedImage pagedImage, int pageSize, IntSize2 fullPageSize, int size, FREE_IMAGE_FORMAT outputFormat, FREE_IMAGE_SAVE_FLAGS saveFlags)
        {
            IntRect serialImageRect = new IntRect();

            MemoryStream[]    memoryStreams = new MemoryStream[size];
            FreeImageBitmap[] pages         = new FreeImageBitmap[size];
            try
            {
                for (int i = 0; i < size; ++i)
                {
                    memoryStreams[i] = new MemoryStream();
                    pages[i]         = new FreeImageBitmap(fullPageSize.Width, fullPageSize.Height, FreeImageAPI.PixelFormat.Format32bppArgb);
                }

                //Calculate pages as tiles, always repeat outer limits
                for (int y = 0; y < size; ++y)
                {
                    serialImageRect.Height = pageSize;
                    serialImageRect.Top    = y * pageSize;

                    Parallel.For(0, size, x =>
                                 //for (int x = 0; x < size; ++x)
                    {
                        IntRect imageRect = serialImageRect;

                        imageRect.Width = pageSize;
                        imageRect.Left  = x * pageSize;

                        using (var pageBox = pages[x].createPixelBox(PixelFormat.PF_A8R8G8B8))
                        {
                            pageBox.Top    += (uint)padding;
                            pageBox.Bottom -= (uint)padding;
                            pageBox.Left   += (uint)padding;
                            pageBox.Right  -= (uint)padding;

                            using (var imageBox = image.createPixelBox())
                            {
                                imageBox.Left   = (uint)imageRect.Left;
                                imageBox.Right  = (uint)imageRect.Right;
                                imageBox.Top    = (uint)imageRect.Top;
                                imageBox.Bottom = (uint)imageRect.Bottom;

                                PixelBox.BulkPixelConversion(imageBox, pageBox);
                            }

                            padFillColor(image, padding, pageSize, fullPageSize, imageRect, pageBox);
                        }
                        //int startPos = (int)stream.Position;
                        pages[x].RotateFlip(RotateFlipType.RotateNoneFlipY); //Have to flip the page over for ogre to be happy
                        pages[x].Save(memoryStreams[x], outputFormat, saveFlags);
                        //pages[x].saveToFile($"page/page{image.Width}_x{x}y_{y}.bmp", FREE_IMAGE_FORMAT.FIF_BMP);
                        memoryStreams[x].Position = 0;
                        //++pagedImage.numImages;
                        //pagedImage.pages.Add(new ImageInfo(startPos, (int)(stream.Position)));
                    });
                    //}

                    for (int x = 0; x < size; ++x)
                    {
                        int startPos = (int)stream.Position;
                        //page.RotateFlip(RotateFlipType.RotateNoneFlipY); //Have to flip the page over for ogre to be happy
                        //page.Save(stream, outputFormat, saveFlags);
                        memoryStreams[x].CopyTo(stream);
                        ++pagedImage.NumImages;
                        pagedImage.Pages.Add(new PagedImage.ImageInfo(startPos, (int)(stream.Position)));
                        memoryStreams[x].Dispose();
                        memoryStreams[x] = new MemoryStream();
                    }
                }
            }
            finally
            {
                for (int i = 0; i < size; ++i)
                {
                    memoryStreams[i].Dispose();
                    pages[i].Dispose();
                }
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Saves a previously loaded FreeImage bitmap to a file.
 /// The format is taken off the filename.
 /// If no suitable format was found false will be returned.
 /// Save flags can be provided by the flags parameter.
 /// </summary>
 /// <param name="dib">Handle to a FreeImage bitmap.</param>
 /// <param name="filename">The complete name of the file to save to.
 /// The extension will be corrected if it is no valid extension for the
 /// selected format or if no extension was specified.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="unloadSource">When true the structure will be unloaded on success.
 /// If the function failed and returned false, the bitmap was not unloaded.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
 public static bool SaveEx(
     ref FIBITMAP dib,
     string filename,
     FREE_IMAGE_SAVE_FLAGS flags,
     bool unloadSource)
 {
     return SaveEx(
         ref dib,
         filename,
         FREE_IMAGE_FORMAT.FIF_UNKNOWN,
         flags,
         FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
         unloadSource);
 }
Ejemplo n.º 16
0
 public static FIBITMAP? ShrinkImageFI(FileInfo fileIn, FileInfo fileOut, Size nuSize, FREE_IMAGE_FORMAT saveFormat, FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS savequality, bool cleanup)
 {
     FIBITMAP? dib = GetJPGImageHandle(fileIn);
       if (dib != null) {
     FIBITMAP ddib = (FIBITMAP)dib;
     ShrinkImageFI(ddib, fileOut, nuSize, filter, savequality);
     if (cleanup) {
       CleanUpResources(ddib);
     }
       }
       return dib;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="dib"></param>
 /// <param name="fileOut"></param>
 /// <param name="savequality"></param>
 /// <returns>true if success</returns>
 public static bool SaveJPGImageHandle(FIBITMAP dib, FileInfo fileOut, FREE_IMAGE_SAVE_FLAGS savequality)
 {
     return FreeImage.SaveEx(dib, fileOut.FullName, savequality);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Saves a previously loaded FreeImage bitmap to a stream.
        /// The stream must be set to the correct position before calling SaveToStream.
        /// </summary>
        /// <param name="dib">Handle to a FreeImage bitmap.</param>
        /// <param name="stream">The stream to write to.</param>
        /// <param name="format">Format of the image.</param>
        /// <param name="flags">Flags to enable or disable plugin-features.</param>
        /// <param name="colorDepth">The new color depth of the bitmap.
        /// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if SaveToStream should
        /// take the best suitable color depth.
        /// If a color depth is selected that the provided format cannot write an
        /// error-message will be thrown.</param>
        /// <param name="unloadSource">When true the structure will be unloaded on success.</param>
        /// <returns>Returns true on success, false on failure.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="stream"/> cannot write.</exception>
        public static bool SaveToStream(
            ref FIBITMAP dib,
            Stream stream,
            FREE_IMAGE_FORMAT format,
            FREE_IMAGE_SAVE_FLAGS flags,
            FREE_IMAGE_COLOR_DEPTH colorDepth,
            bool unloadSource)
        {
            if (dib.IsNull)
            {
                throw new ArgumentNullException("dib");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanWrite)
            {
                throw new ArgumentException("stream is not capable of writing.");
            }
            if ((!FIFSupportsWriting(format)) || (!FIFSupportsExportType(format, FREE_IMAGE_TYPE.FIT_BITMAP)))
            {
                return false;
            }

            FIBITMAP dibToSave = PrepareBitmapColorDepth(dib, format, colorDepth);
            bool result = false;

            try
            {
                // Create a 'FreeImageIO' structure for calling 'SaveToHandle'
                FreeImageIO io = FreeImageStreamIO.io;

                using (fi_handle handle = new fi_handle(stream))
                {
                    result = SaveToHandle(format, dibToSave, ref io, handle, flags);
                }
            }
            catch
            {
                // Always unload a temporary created bitmap.
                if (dibToSave != dib)
                {
                    UnloadEx(ref dibToSave);
                }
                // On success unload the bitmap
                if (result && unloadSource)
                {
                    UnloadEx(ref dib);
                }
            }

            return result;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Saves a previously loaded FreeImage bitmap to a stream.
 /// The stream must be set to the correct position before calling SaveToStream.
 /// </summary>
 /// <param name="dib">Handle to a FreeImage bitmap.</param>
 /// <param name="stream">The stream to write to.</param>
 /// <param name="format">Format of the image.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="colorDepth">The new color depth of the bitmap.
 /// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if SaveToStream should
 /// take the best suitable color depth.
 /// If a color depth is selected that the provided format cannot write an
 /// error-message will be thrown.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="stream"/> cannot write.</exception>
 public static bool SaveToStream(
     FIBITMAP dib,
     Stream stream,
     FREE_IMAGE_FORMAT format,
     FREE_IMAGE_SAVE_FLAGS flags,
     FREE_IMAGE_COLOR_DEPTH colorDepth)
 {
     return SaveToStream(
         ref dib,
         stream,
         format,
         flags,
         colorDepth,
         false);
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Saves a previously loaded FreeImage bitmap to a stream.
 /// The stream must be set to the correct position before calling SaveToStream.
 /// </summary>
 /// <param name="dib">Handle to a FreeImage bitmap.</param>
 /// <param name="stream">The stream to write to.</param>
 /// <param name="format">Format of the image.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="unloadSource">When true the structure will be unloaded on success.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="dib"/> or <paramref name="stream"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="stream"/> cannot write.</exception>
 public static bool SaveToStream(
     ref FIBITMAP dib,
     Stream stream,
     FREE_IMAGE_FORMAT format,
     FREE_IMAGE_SAVE_FLAGS flags,
     bool unloadSource)
 {
     return SaveToStream(
         ref dib, stream,
         format,
         flags,
         FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
         unloadSource);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Saves a previously loaded FreeImage bitmap to a file.
        /// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
        /// the format is taken off the filename.
        /// If no suitable format was found false will be returned.
        /// Save flags can be provided by the flags parameter.
        /// The bitmaps color depth can be set by 'colorDepth'.
        /// If set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> a suitable color depth
        /// will be taken if available.
        /// </summary>
        /// <param name="dib">Handle to a FreeImage bitmap.</param>
        /// <param name="filename">The complete name of the file to save to.
        /// The extension will be corrected if it is no valid extension for the
        /// selected format or if no extension was specified.</param>
        /// <param name="format">Format of the image. If the format should be taken from the
        /// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
        /// <param name="flags">Flags to enable or disable plugin-features.</param>
        /// <param name="colorDepth">The new color depth of the bitmap.
        /// Set to <see cref="FREE_IMAGE_COLOR_DEPTH.FICD_AUTO"/> if Save should take the
        /// best suitable color depth.
        /// If a color depth is selected that the provided format cannot write an
        /// error-message will be thrown.</param>
        /// <param name="unloadSource">When true the structure will be unloaded on success.
        /// If the function failed and returned false, the bitmap was not unloaded.</param>
        /// <returns>Returns true on success, false on failure.</returns>
        /// <exception cref="ArgumentException">
        /// A direct color conversion failed.</exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
        public static bool SaveEx(
            ref FIBITMAP dib,
            string filename,
            FREE_IMAGE_FORMAT format,
            FREE_IMAGE_SAVE_FLAGS flags,
            FREE_IMAGE_COLOR_DEPTH colorDepth,
            bool unloadSource)
        {
            if (dib.IsNull)
            {
                throw new ArgumentNullException("dib");
            }
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }
            bool result = false;
            // Gets format from filename if the format is unknown
            if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
            {
                format = GetFIFFromFilename(filename);
            }
            if (format != FREE_IMAGE_FORMAT.FIF_UNKNOWN)
            {
                // Checks writing support
                if (FIFSupportsWriting(format) && FIFSupportsExportType(format, GetImageType(dib)))
                {
                    // Check valid filename and correct it if needed
                    if (!IsFilenameValidForFIF(format, filename))
                    {
                        int index = filename.LastIndexOf('.');
                        string extension = GetPrimaryExtensionFromFIF(format);

                        if (index == -1)
                        {
                            // We have no '.' (dot) so just add the extension
                            filename += "." + extension;
                        }
                        else
                        {
                            // Overwrite the old extension
                            filename = filename.Substring(0, filename.LastIndexOf('.')) + extension;
                        }
                    }

                    FIBITMAP dibToSave = PrepareBitmapColorDepth(dib, format, colorDepth);
                    result = Save(format, dibToSave, filename, flags);

                    // Always unload a temporary created bitmap.
                    if (dibToSave != dib)
                    {
                        UnloadEx(ref dibToSave);
                    }
                    // On success unload the bitmap
                    if (result && unloadSource)
                    {
                        UnloadEx(ref dib);
                    }
                }
            }
            return result;
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Saves a previously loaded FreeImage bitmap to a file.
 /// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
 /// the format is taken off the filename.
 /// If no suitable format was found false will be returned.
 /// Save flags can be provided by the flags parameter.
 /// </summary>
 /// <param name="dib">Handle to a FreeImage bitmap.</param>
 /// <param name="filename">The complete name of the file to save to.
 /// The extension will be corrected if it is no valid extension for the
 /// selected format or if no extension was specified.</param>
 /// <param name="format">Format of the image. If the format should be taken from the
 /// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="dib"/> or <paramref name="filename"/> is null.</exception>
 public static bool SaveEx(
     FIBITMAP dib,
     string filename,
     FREE_IMAGE_FORMAT format,
     FREE_IMAGE_SAVE_FLAGS flags)
 {
     return SaveEx(
         ref dib,
         filename,
         format,
         flags,
         FREE_IMAGE_COLOR_DEPTH.FICD_AUTO,
         false);
 }
Ejemplo n.º 23
0
        private void convert(string srcPath, string dstPath, int icoSize, int bpp)
        {
            string srcSuffix = Path.GetExtension(srcPath).ToLower();
            string dstSuffix = Path.GetExtension(dstPath).ToLower();

            //bool isDir = Directory.Exists(srcPath);

            // save
            try {
                FIBITMAP dib;
                switch (srcSuffix)
                {
                case ".ico": {
                    dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_ICO, srcPath, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
                    break;
                }

                case ".bmp": {
                    dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_BMP, srcPath, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
                    break;
                }

                case ".jpg": {
                    dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, srcPath, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
                    break;
                }

                case ".png": {
                    dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_PNG, srcPath, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
                    break;
                }

                default: {
                    Bitmap img = FileIcon.getIcon(srcPath, icoSize);
                    if (img == null)
                    {
                        return;
                    }
                    dib = FreeImage.CreateFromBitmap(img);
                    break;
                    //return;
                }
                }
                //FIBITMAP dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_PNG, srcPath, FREE_IMAGE_LOAD_FLAGS.DEFAULT);
                uint width  = FreeImage.GetWidth(dib);
                uint height = FreeImage.GetHeight(dib);
                //FIBITMAP dibTmp = FreeImage.Rescale(dib, icoSize, icoSize, FREE_IMAGE_FILTER.FILTER_BICUBIC);

                FIBITMAP dibOut = formatImage(dib, icoSize, bpp);

                FREE_IMAGE_FORMAT     format = FREE_IMAGE_FORMAT.FIF_ICO;
                FREE_IMAGE_SAVE_FLAGS flag   = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE;
                switch (dstSuffix)
                {
                case ".png": format = FREE_IMAGE_FORMAT.FIF_PNG; flag = FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION; break;

                case ".jpg": format = FREE_IMAGE_FORMAT.FIF_JPEG; flag = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD; break;

                case ".bmp": format = FREE_IMAGE_FORMAT.FIF_BMP; flag = FREE_IMAGE_SAVE_FLAGS.BMP_SAVE_RLE; break;

                case ".ico":
                default: break;
                }
                FreeImage.Save(format, dibOut, dstPath, flag);
                //bool isOk = FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, dibOut, dstPath + ".png", FREE_IMAGE_SAVE_FLAGS.PNG_INTERLACED);
                FreeImage.Unload(dibOut);
                FreeImage.Unload(dib);
            } catch (Exception ex) { Debug.WriteLine(ex.ToString()); }
        }
        public static void SaveJpeg(Image img, Stream stream,
                                    FreeImageJpegQualityType freeImageJpegQualityType, FreeImageJpegSubSamplingType freeImageJpegSubSamplingType)
        {
            using (FreeImageAPI.FreeImageBitmap fib = new FreeImageAPI.FreeImageBitmap(img))
            {
                FREE_IMAGE_SAVE_FLAGS jpgQuality     = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                FREE_IMAGE_SAVE_FLAGS jpgSubSampling = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;

                switch (freeImageJpegQualityType)
                {
                case FreeImageJpegQualityType.JPEG_QUALITYAVERAGE:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                    break;

                case FreeImageJpegQualityType.JPEG_QUALITYBAD:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;
                    break;

                case FreeImageJpegQualityType.JPEG_QUALITYGOOD:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                    break;

                case FreeImageJpegQualityType.JPEG_QUALITYNORMAL:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                    break;

                case FreeImageJpegQualityType.JPEG_QUALITYSUPERB:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                    break;

                case FreeImageJpegQualityType.JPEG_PROGRESSIVE_QUALITYAVERAGE:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                    break;

                case FreeImageJpegQualityType.JPEG_PROGRESSIVE_QUALITYBAD:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;
                    break;

                case FreeImageJpegQualityType.JPEG_PROGRESSIVE_QUALITYGOOD:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                    break;

                case FreeImageJpegQualityType.JPEG_PROGRESSIVE_QUALITYNORMAL:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                    break;

                case FreeImageJpegQualityType.JPEG_PROGRESSIVE_QUALITYSUPERB:
                    jpgQuality = FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                    break;
                }

                switch (freeImageJpegSubSamplingType)
                {
                case FreeImageJpegSubSamplingType.JPEG_SUBSAMPLING_411:
                    jpgSubSampling = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_411;
                    break;

                case FreeImageJpegSubSamplingType.JPEG_SUBSAMPLING_420:
                    jpgSubSampling = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420;
                    break;

                case FreeImageJpegSubSamplingType.JPEG_SUBSAMPLING_422:
                    jpgSubSampling = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_422;
                    break;

                case FreeImageJpegSubSamplingType.JPEG_SUBSAMPLING_444:
                    jpgSubSampling = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;
                    break;
                }

                fib.Save(stream, FreeImageAPI.FREE_IMAGE_FORMAT.FIF_JPEG, jpgQuality | jpgSubSampling);
            }
        }
Ejemplo n.º 25
0
 public static void ShrinkImageFI(FIBITMAP dib, FileInfo fileOut, Size nuSize, FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS savequality)
 {
     FIBITMAP dibsmall = GetShrinkedDIB(dib, nuSize, filter);
       SaveJPGImageHandle(dibsmall, fileOut, savequality);
       CleanUpResources(dibsmall);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
 /// </summary>
 /// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
 /// <param name="filename">Name of the file to save to.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// The bitmaps pixelformat is invalid.</exception>
 public static bool SaveBitmap(
     Bitmap bitmap,
     string filename,
     FREE_IMAGE_SAVE_FLAGS flags)
 {
     return SaveBitmap(
         bitmap,
         filename,
         FREE_IMAGE_FORMAT.FIF_UNKNOWN,
         flags);
 }
Ejemplo n.º 27
0
        public FreeImageEncoderPlugin(ResizeSettings settings, object original)
        {
            ImageFormat originalFormat = DefaultEncoder.GetOriginalFormat(original);

            if (!IsValidOutputFormat(originalFormat))
            {
                originalFormat = ImageFormat.Jpeg;                                      //No valid info available about the original format. Use Jpeg.
            }
            //What format was specified?
            ImageFormat requestedFormat = DefaultEncoder.GetRequestedFormat(settings.Format, originalFormat); //fallback to originalFormat if not specified.

            if (!IsValidOutputFormat(requestedFormat))
            {
                throw new ArgumentException("An unrecognized or unsupported output format (" + (settings.Format != null ? settings.Format : "(null)") + ") was specified in 'settings'.");
            }
            this.format = FreeImage.GetFormat(requestedFormat);

            //Parse JPEG settings.
            int quality = 90;

            if (string.IsNullOrEmpty(settings["quality"]) || !int.TryParse(settings["quality"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out quality))
            {
                quality = 90;
            }
            if (format == FREE_IMAGE_FORMAT.FIF_JPEG)
            {
                if (quality >= 100)
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB;
                }
                else if (quality >= 75)
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD;
                }
                else if (quality >= 50)
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;
                }
                else if (quality >= 25)
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYAVERAGE;
                }
                else
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYBAD;
                }


                if ("true".Equals(settings["progressive"]))
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE;
                }

                if ("411".Equals(settings["subsampling"]))
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_411;
                }
                if ("420".Equals(settings["subsampling"]))
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420;
                }
                if ("422".Equals(settings["subsampling"]))
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_422;
                }
                if ("444".Equals(settings["subsampling"]))
                {
                    encodingOptions |= FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444;
                }
            }
            if (string.IsNullOrEmpty(settings["colors"]) || !int.TryParse(settings["colors"], NumberStyles.Number, NumberFormatInfo.InvariantInfo, out colors))
            {
                colors = -1;
            }


            if (format == FREE_IMAGE_FORMAT.FIF_GIF)
            {
                //encodingOptions = FREE_IMAGE_SAVE_FLAGS.
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create a paged image from a FreeImageBitmap instance, note that this function is destructive
        /// to the passed in FreeImageBitmap since it will resize it while creating all the mip levels
        /// for the paged image. However, you will still need to dispose the image you pass in, this class
        /// makes a copy while destroying the image, but does not take ownership of the original.
        /// </summary>
        /// <param name="image">The image to extract pages from.</param>
        /// <param name="pageSize">The size of the pages to extract.</param>
        public static void fromBitmap(FreeImageBitmap image, int pageSize, int padding, Stream stream, ImageType imageType, int maxSize, bool lossless, FREE_IMAGE_FILTER filter, ImagePageSizeStrategy pageSizeStrategy, Action <FreeImageBitmap> afterResize = null)
        {
            stream.Seek(HeaderSize, SeekOrigin.Begin); //Leave some space for the header

            if (image.Width > maxSize)
            {
                Logging.Log.Info("Image size {0} was too large, resizing to {1}", image.Width, maxSize);
                pageSizeStrategy.rescaleImage(image, new Size(maxSize, maxSize), filter);
            }

            PagedImage            pagedImage = new PagedImage();
            int                   padding2x  = padding * 2;
            FREE_IMAGE_FORMAT     outputFormat;
            FREE_IMAGE_SAVE_FLAGS saveFlags = FREE_IMAGE_SAVE_FLAGS.DEFAULT;

            switch (imageType)
            {
            default:
            case ImageType.PNG:
                outputFormat = FREE_IMAGE_FORMAT.FIF_PNG;
                break;

            case ImageType.WEBP:
                outputFormat = FREE_IMAGE_FORMAT.FIF_WEBP;
                if (lossless)
                {
                    saveFlags = FREE_IMAGE_SAVE_FLAGS.WEBP_LOSSLESS;
                }
                else
                {
                    saveFlags = (FREE_IMAGE_SAVE_FLAGS)90;
                }
                break;
            }

            //Kind of weird, ogre and freeimage are backwards from one another in terms of scanline 0 being the top or bottom
            //This easily fixes the math below by just flipping the image first. Note that pages must be flipped back over because
            //of this when they are saved.
            image.RotateFlip(RotateFlipType.RotateNoneFlipY);

            pagedImage.numImages  = 0;
            pagedImage.imageType  = (int)imageType;
            pagedImage.imageXSize = image.Width;
            pagedImage.imageYSize = image.Height;
            pagedImage.pageSize   = pageSize;
            if (pagedImage.imageXSize != pagedImage.imageYSize)
            {
                throw new InvalidDataException("Image must be a square");
            }

            int mipLevelCount = 0;
            int numPages      = 0;

            for (int i = pagedImage.imageXSize; i >= pageSize; i >>= 1)
            {
                ++mipLevelCount;
                int pagesForMip = i / pageSize;
                numPages += pagesForMip * pagesForMip;
            }
            pagedImage.pages      = new List <ImageInfo>(numPages);
            pagedImage.mipIndices = new List <MipIndexInfo>(mipLevelCount);

            IntSize2 fullPageSize = new IntSize2(pageSize + padding2x, pageSize + padding2x);

            for (int mip = 0; mip < mipLevelCount; ++mip)
            {
                //Setup mip level
                if (mip != 0)
                {
                    pageSizeStrategy.rescaleImage(image, new Size(image.Width >> 1, image.Height >> 1), filter);
                    if (afterResize != null)
                    {
                        //Flip so external functions aren't confused
                        image.RotateFlip(RotateFlipType.RotateNoneFlipY);
                        afterResize(image);
                        //Flip back for correct math
                        image.RotateFlip(RotateFlipType.RotateNoneFlipY);
                    }
                }
                int size = image.Width / pageSize;
                pagedImage.mipIndices.Add(new MipIndexInfo(pagedImage.numImages, size));
                pageSizeStrategy.extractPage(image, padding, stream, pagedImage, pageSize, fullPageSize, size, outputFormat, saveFlags);
            }

            //Write half size mip
            int      halfPageSize   = pageSize >> 1;
            IntSize2 halfSizePadded = new IntSize2(halfPageSize + padding2x, halfPageSize + padding2x);

            pageSizeStrategy.rescaleImage(image, new Size(image.Width >> 1, image.Height >> 1), filter);
            pageSizeStrategy.extractPage(image, padding, stream, pagedImage, halfPageSize, halfSizePadded, 1, outputFormat, saveFlags);

            pagedImage.indexStart = (int)stream.Position;

            using (BinaryWriter sw = new BinaryWriter(stream, EncodingShim.Default, true))
            {
                foreach (var imageInfo in pagedImage.pages)
                {
                    imageInfo.write(sw);
                }

                //Go back to header reserved space
                sw.BaseStream.Seek(0, SeekOrigin.Begin);
                sw.Write(MagicNumber);
                sw.Write(pagedImage.numImages);
                sw.Write(pagedImage.imageType);
                sw.Write(pagedImage.imageXSize);
                sw.Write(pagedImage.imageYSize);
                sw.Write(pagedImage.pageSize);
                sw.Write(pagedImage.indexStart);
            }
        }
Ejemplo n.º 29
0
 private static extern bool CloseMultiBitmap_Windows(FIMULTIBITMAP bitmap, FREE_IMAGE_SAVE_FLAGS flags);
Ejemplo n.º 30
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.º 31
0
 private static extern bool SaveWindows(FREE_IMAGE_FORMAT fif, FIBITMAP dib, [MarshalAs(UnmanagedType.LPStr)] string filename, FREE_IMAGE_SAVE_FLAGS flags);
 public static extern bool SaveToMemory(FREE_IMAGE_FORMAT fif, FIBITMAP dib, FIMEMORY stream, FREE_IMAGE_SAVE_FLAGS flags);
Ejemplo n.º 33
0
 private static extern bool SaveUWindows(FREE_IMAGE_FORMAT fif, FIBITMAP dib, string filename, FREE_IMAGE_SAVE_FLAGS flags);
 private static extern bool SaveU(FREE_IMAGE_FORMAT fif, FIBITMAP dib, string filename, FREE_IMAGE_SAVE_FLAGS flags);
    // public Texture2D testTexture;
    public void SaveImage(Texture2D texture, string imagePath, ChannelsPerMap exportChannels, bool convertTo16 = false, bool waitForThread = false)
    {
        //  testTexture = texture;
        var format = texture.format;
        FREE_IMAGE_SAVE_FLAGS saveFlags  = FREE_IMAGE_SAVE_FLAGS.DEFAULT;
        FREE_IMAGE_FORMAT     destFormat = FREE_IMAGE_FORMAT.FIF_BMP;
        var saveType = System.IO.Path.GetExtension(imagePath);

        switch (saveType)
        {
        case ".png":
            destFormat = FREE_IMAGE_FORMAT.FIF_PNG;
            saveFlags  = FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_SPEED;
            if (format == TextureFormat.RGBAFloat && !convertTo16)
            {
                Debug.LogError("Can't save HDR image as PNG");
                return;
                //dib = FreeImage.TmoDrago03(dib, 1, 1);
            }
            break;

        case ".exr":
            destFormat = FREE_IMAGE_FORMAT.FIF_EXR;
            saveFlags  = FREE_IMAGE_SAVE_FLAGS.EXR_FLOAT | FREE_IMAGE_SAVE_FLAGS.EXR_PIZ;
            break;

        case ".tif":
        case ".tiff":
            destFormat = FREE_IMAGE_FORMAT.FIF_TIFF;
            saveFlags  = FREE_IMAGE_SAVE_FLAGS.TIFF_LZW;
            break;

        case ".tga":
            destFormat = FREE_IMAGE_FORMAT.FIF_TARGA;
            saveFlags  = FREE_IMAGE_SAVE_FLAGS.EXR_NONE;            // same value as TARGA_SAVE_RLE (not present in FreeImage.NET for some reason)
            if (format == TextureFormat.RGBAFloat)
            {
                Debug.LogError("Can't save HDR image as TGA");
                return;
            }
            break;

        case ".psd":
            destFormat = FREE_IMAGE_FORMAT.FIF_PSD;
            break;

        case ".jpg":
        case ".jpeg":
            destFormat = FREE_IMAGE_FORMAT.FIF_JPEG;
            saveFlags  = FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB | FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_420 | FREE_IMAGE_SAVE_FLAGS.JPEG_OPTIMIZE;
            break;
        }
        Debug.Log("destFormat: " + destFormat);

        //int bppDest = 0;
        //int bppSource = 0;
        var rawBytes = texture.GetRawTextureData();

        Debug.Log("texture2d.width, texture2d.height, format:" + texture.width + ", " + texture.height + " , " + format);

        int texwidth  = texture.width;
        int texheight = texture.height;

        Destroy(texture);
        Resources.UnloadUnusedAssets();

        //Create new thread then save image to file
        if (waitForThread || texwidth >= 8096)
        {
            Debug.Log("Saving image synchronously.");
            SaveHelper(format, rawBytes, texwidth, texheight, convertTo16, exportChannels, imagePath, destFormat, saveFlags);
        }
        else
        {
            new System.Threading.Thread(() =>
            {
                Debug.Log("Saving image asynchronously with threads.");
                SaveHelper(format, rawBytes, texwidth, texheight, convertTo16, exportChannels, imagePath, destFormat, saveFlags);
            }).Start();
        }
        //if (waitForThread)
        //{
        //    newThread.Join();
        //}
    }
Ejemplo n.º 36
0
 private static extern bool FreeImage_Save(FREE_IMAGE_FORMAT fif, FIBITMAP dib, string filename, FREE_IMAGE_SAVE_FLAGS flags);
Ejemplo n.º 37
0
        public void extractPage(FreeImageBitmap image, int padding, Stream stream, PagedImage pagedImage, int pageSize, IntSize2 fullPageSize, int size, FREE_IMAGE_FORMAT outputFormat, FREE_IMAGE_SAVE_FLAGS saveFlags)
        {
            bool    topSide, bottomSide;
            IntRect serialImageRect = new IntRect();

            MemoryStream[]    memoryStreams = new MemoryStream[size];
            FreeImageBitmap[] pages         = new FreeImageBitmap[size];
            try
            {
                for (int i = 0; i < size; ++i)
                {
                    memoryStreams[i] = new MemoryStream();
                    pages[i]         = new FreeImageBitmap(fullPageSize.Width, fullPageSize.Height, FreeImageAPI.PixelFormat.Format32bppArgb);
                }

                //Calculate pages, note that there is overlap by padding between them this is intentional
                for (int y = 0; y < size; ++y)
                {
                    serialImageRect.Height = fullPageSize.Height;
                    serialImageRect.Top    = y * pageSize - padding;
                    topSide = serialImageRect.Top < 0;
                    if (topSide)
                    {
                        serialImageRect.Top     = 0;
                        serialImageRect.Height -= padding;
                    }

                    bottomSide = serialImageRect.Bottom > image.Height;
                    if (bottomSide)
                    {
                        if (topSide)
                        {
                            //Take entire image
                            serialImageRect.Top    = 0;
                            serialImageRect.Height = image.Height;
                        }
                        else
                        {
                            //Extra row on top, bottom flush with texture bottom will add extra pixel row on bottom will add extra pixel row on bottom below
                            serialImageRect.Top     = image.Height - pageSize - padding;
                            serialImageRect.Height -= padding;
                        }
                    }

                    Parallel.For(0, size, x =>
                                 //for (int x = 0; x < size; ++x)
                    {
                        bool leftSide, rightSide;
                        IntRect imageRect = serialImageRect;

                        imageRect.Width = fullPageSize.Width;
                        imageRect.Left  = x * pageSize - padding;
                        leftSide        = imageRect.Left < 0;
                        if (leftSide)
                        {
                            imageRect.Left   = 0;
                            imageRect.Width -= padding;
                        }

                        rightSide = imageRect.Right > image.Width;
                        if (rightSide)
                        {
                            if (leftSide)
                            {
                                //Take entire image
                                imageRect.Left  = 0;
                                imageRect.Width = image.Width;
                            }
                            else
                            {
                                //Extra row on left, right flush with texture right will add extra pixel row on right below
                                imageRect.Left   = image.Width - pageSize - padding;
                                imageRect.Width -= padding;
                            }
                        }

                        using (var pageBox = pages[x].createPixelBox(PixelFormat.PF_A8R8G8B8))
                        {
                            if (topSide)
                            {
                                pageBox.Top += (uint)padding;
                            }

                            if (bottomSide)
                            {
                                pageBox.Bottom -= (uint)padding;
                            }

                            if (leftSide)
                            {
                                pageBox.Left += (uint)padding;
                            }

                            if (rightSide)
                            {
                                pageBox.Right -= (uint)padding;
                            }

                            using (var imageBox = image.createPixelBox())
                            {
                                imageBox.Left   = (uint)imageRect.Left;
                                imageBox.Right  = (uint)imageRect.Right;
                                imageBox.Top    = (uint)imageRect.Top;
                                imageBox.Bottom = (uint)imageRect.Bottom;

                                PixelBox.BulkPixelConversion(imageBox, pageBox);
                            }

                            if (topSide)
                            {
                                using (PixelBox altSrcBox = image.createPixelBox())
                                {
                                    pageBox.Top    = 0;
                                    pageBox.Bottom = (uint)padding;
                                    pageBox.Left   = (uint)padding;
                                    pageBox.Right  = (uint)(fullPageSize.Width - padding);

                                    altSrcBox.Top    = (uint)imageRect.Top;
                                    altSrcBox.Bottom = (uint)(imageRect.Top + padding);
                                    altSrcBox.Left   = (uint)imageRect.Left;
                                    altSrcBox.Right  = (uint)(imageRect.Left + pageSize);

                                    PixelBox.BulkPixelConversion(altSrcBox, pageBox);
                                }
                            }

                            if (bottomSide)
                            {
                                using (PixelBox altSrcBox = image.createPixelBox())
                                {
                                    pageBox.Top    = (uint)(fullPageSize.Height - padding);
                                    pageBox.Bottom = (uint)fullPageSize.Height;
                                    pageBox.Left   = (uint)padding;
                                    pageBox.Right  = (uint)(fullPageSize.Width - padding);

                                    altSrcBox.Top    = (uint)(imageRect.Bottom - padding);
                                    altSrcBox.Bottom = (uint)imageRect.Bottom;
                                    altSrcBox.Left   = (uint)imageRect.Left;
                                    altSrcBox.Right  = (uint)(imageRect.Left + pageSize);

                                    PixelBox.BulkPixelConversion(altSrcBox, pageBox);
                                }
                            }

                            if (leftSide)
                            {
                                using (PixelBox altSrcBox = image.createPixelBox())
                                {
                                    pageBox.Top    = (uint)padding;
                                    pageBox.Bottom = (uint)(fullPageSize.Height - padding);
                                    pageBox.Left   = 0;
                                    pageBox.Right  = (uint)padding;

                                    altSrcBox.Top    = (uint)imageRect.Top;
                                    altSrcBox.Bottom = (uint)(imageRect.Top + pageSize);
                                    altSrcBox.Left   = (uint)imageRect.Left;
                                    altSrcBox.Right  = (uint)(imageRect.Left + padding);

                                    PixelBox.BulkPixelConversion(altSrcBox, pageBox);
                                }
                            }

                            if (rightSide)
                            {
                                using (PixelBox altSrcBox = image.createPixelBox())
                                {
                                    pageBox.Top    = (uint)padding;
                                    pageBox.Bottom = (uint)(fullPageSize.Height - padding);
                                    pageBox.Left   = (uint)(fullPageSize.Width - padding);
                                    pageBox.Right  = (uint)fullPageSize.Width;

                                    altSrcBox.Top    = (uint)imageRect.Top;
                                    altSrcBox.Bottom = (uint)(imageRect.Top + pageSize);
                                    altSrcBox.Left   = (uint)(imageRect.Right - padding);
                                    altSrcBox.Right  = (uint)imageRect.Right;

                                    PixelBox.BulkPixelConversion(altSrcBox, pageBox);
                                }
                            }
                        }
                        //int startPos = (int)stream.Position;
                        pages[x].RotateFlip(RotateFlipType.RotateNoneFlipY); //Have to flip the page over for ogre to be happy
                        pages[x].Save(memoryStreams[x], outputFormat, saveFlags);
                        memoryStreams[x].Position = 0;
                        //++pagedImage.numImages;
                        //pagedImage.pages.Add(new ImageInfo(startPos, (int)(stream.Position)));
                    });
                    //}

                    for (int x = 0; x < size; ++x)
                    {
                        int startPos = (int)stream.Position;
                        //page.RotateFlip(RotateFlipType.RotateNoneFlipY); //Have to flip the page over for ogre to be happy
                        //page.Save(stream, outputFormat, saveFlags);
                        memoryStreams[x].CopyTo(stream);
                        ++pagedImage.NumImages;
                        pagedImage.Pages.Add(new PagedImage.ImageInfo(startPos, (int)(stream.Position)));
                        memoryStreams[x].Dispose();
                        memoryStreams[x] = new MemoryStream();
                    }
                }
            }
            finally
            {
                for (int i = 0; i < size; ++i)
                {
                    memoryStreams[i].Dispose();
                    pages[i].Dispose();
                }
            }
        }
Ejemplo n.º 38
0
        public bool Save(string filename, FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN, FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.DEFAULT)
        {
            if (dib.IsNull) return false;

            return FreeImage.SaveEx(dib, filename, format, flags);
        }
Ejemplo n.º 39
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dib"></param>
 /// <param name="fileOut"></param>
 /// <param name="savequality"></param>
 /// <returns>true if success</returns>
 public static bool SaveJPGImageHandle(FIBITMAP dib, FileInfo fileOut, FREE_IMAGE_SAVE_FLAGS savequality)
 {
     return(FreeImage.SaveEx(dib, fileOut.FullName, savequality));
 }
Ejemplo n.º 40
0
        public static FIBITMAP?ShrinkImageFI(FileInfo fileIn, FileInfo fileOut, Size nuSize, FREE_IMAGE_FORMAT saveFormat, FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS savequality, bool cleanup)
        {
            FIBITMAP?dib = GetJPGImageHandle(fileIn);

            if (dib != null)
            {
                FIBITMAP ddib = (FIBITMAP)dib;
                ShrinkImageFI(ddib, fileOut, nuSize, filter, savequality);
                if (cleanup)
                {
                    CleanUpResources(ddib);
                }
            }
            return(dib);
        }
Ejemplo n.º 41
0
        public static void ShrinkImageFI(FIBITMAP dib, FileInfo fileOut, Size nuSize, FREE_IMAGE_FILTER filter, FREE_IMAGE_SAVE_FLAGS savequality)
        {
            FIBITMAP dibsmall = GetShrinkedDIB(dib, nuSize, filter);

            SaveJPGImageHandle(dibsmall, fileOut, savequality);
            CleanUpResources(dibsmall);
        }
Ejemplo n.º 42
0
 private static extern bool SaveToMemoryWindows(FREE_IMAGE_FORMAT fif, FIBITMAP dib, FIMEMORY stream, FREE_IMAGE_SAVE_FLAGS flags);
Ejemplo n.º 43
0
 /// <summary>
 /// Saves a .NET <see cref="System.Drawing.Bitmap"/> to a file.
 /// </summary>
 /// <param name="bitmap">The .NET <see cref="System.Drawing.Bitmap"/> to save.</param>
 /// <param name="filename">Name of the file to save to.</param>
 /// <param name="format">Format of the bitmap. If the format should be taken from the
 /// filename use <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Returns true on success, false on failure.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="bitmap"/> or <paramref name="filename"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// The bitmaps pixelformat is invalid.</exception>
 public static bool SaveBitmap(
     Bitmap bitmap,
     string filename,
     FREE_IMAGE_FORMAT format,
     FREE_IMAGE_SAVE_FLAGS flags)
 {
     FIBITMAP dib = CreateFromBitmap(bitmap);
     bool result = SaveEx(dib, filename, format, flags);
     Unload(dib);
     return result;
 }
    private void SaveHelper(TextureFormat format, byte[] rawBytes, int texwidth, int texheight, bool convertTo16,
                            ChannelsPerMap exportChannels, string imagePath, FREE_IMAGE_FORMAT destFormat, FREE_IMAGE_SAVE_FLAGS saveFlags)
    {
        int             bytesPerPixel = 4;
        FREE_IMAGE_TYPE imageType     = FREE_IMAGE_TYPE.FIT_BITMAP;

        switch (format)
        {
        case TextureFormat.RGBAHalf:
            imageType     = FREE_IMAGE_TYPE.FIT_RGBA16;
            bytesPerPixel = 8;
            break;

        case TextureFormat.RGBAFloat:
            imageType     = FREE_IMAGE_TYPE.FIT_RGBAF;
            bytesPerPixel = 16;
            break;

        case TextureFormat.ARGB32:
            imageType     = FREE_IMAGE_TYPE.FIT_BITMAP;
            bytesPerPixel = 4;
            //tex.GetPixels32();
            //ConvertBGRAtoARGBScanline(dib);
            // convert back to ARGB
            if (FreeImage.IsLittleEndian())
            {
                for (int j = 0; j < rawBytes.Length; j += 4)
                {
                    // convert BGRA to ARGB
                    var a = rawBytes[j];
                    var r = rawBytes[j + 1];
                    rawBytes[j]     = rawBytes[j + 3];
                    rawBytes[j + 1] = rawBytes[j + 2];
                    rawBytes[j + 2] = r;
                    rawBytes[j + 3] = a;
                }
            }
            break;

        case TextureFormat.RGB24:
            imageType     = FREE_IMAGE_TYPE.FIT_BITMAP;
            bytesPerPixel = 3;
            if (FreeImage.IsLittleEndian())
            {
                // convert back to RGB
                for (int i = 0; i < rawBytes.Length; i += 3)
                {
                    // convert BGR to RGB
                    var r = rawBytes[i];
                    rawBytes[i]     = rawBytes[i + 2];
                    rawBytes[i + 2] = r;
                }
            }
            break;
        }



        FIBITMAP dib = FreeImage.ConvertFromRawBits(rawBytes, imageType, texwidth, texheight, texwidth * bytesPerPixel, (uint)bytesPerPixel * 8, 0, 0, 0, false);

        if (dib.IsNull)
        {
            Debug.LogError("Dib is NULL!!!");
        }
        rawBytes = null;
        GC.Collect();
        if (convertTo16)
        {
            dib    = FreeImage.ConvertToType(dib, FREE_IMAGE_TYPE.FIT_RGBA16, false);
            format = TextureFormat.RGBAHalf;
        }

        switch (exportChannels)
        {
        case ChannelsPerMap.RGB:
            // remove alpha channel
            switch (format)
            {
            case TextureFormat.RGBAFloat:
                dib = FreeImage.ConvertToRGBF(dib);
                break;

            case TextureFormat.RGBAHalf:
                dib = FreeImage.ConvertToType(dib, FREE_IMAGE_TYPE.FIT_RGB16, false);
                break;

            case TextureFormat.ARGB32:
                dib = FreeImage.ConvertTo24Bits(dib);
                break;
            }
            break;

        case ChannelsPerMap.R:
            dib = FreeImage.GetChannel(dib, FREE_IMAGE_COLOR_CHANNEL.FICC_RED);
            break;

        // if already RGBA don't need to do any conversion
        default:
            break;
        }

        try
        {
            using (FileStream saveStream = new FileStream(imagePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                Debug.Log("FreeImage::FileSaveSuccess: " + imagePath + " :" + FreeImage.SaveToStream(ref dib, saveStream, destFormat, saveFlags, true));
            }
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            //progressBar.DoneProgress();
            FreeImage.UnloadEx(ref dib);
            throw;
        }
        //if (progressBar != null)
        //{
        //    UnityThreadHelper.Dispatcher.Dispatch(() =>
        //    {
        //        progressBar.Increment();
        //    });
        //}
    }
Ejemplo n.º 45
0
        public bool Save(string filename, FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN, FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.DEFAULT)
        {
            if (dib.IsNull)
            {
                return(false);
            }

            return(FreeImage.SaveEx(dib, filename, format, flags));
        }