Ejemplo n.º 1
0
        /// <summary>
        /// Load a FreeImage bitmap specifying different flags according to the file extension
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private FreeImageBitmap LoadBitmap(string fileName)
        {
            FREE_IMAGE_LOAD_FLAGS flags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;

            // Rotate Jpegs if possible
            if (fileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith("jpeg", StringComparison.OrdinalIgnoreCase))
            {
                flags = FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE | FREE_IMAGE_LOAD_FLAGS.JPEG_EXIFROTATE;
            }

            // Load the image from disk
            try
            {
                var bmp = new FreeImageBitmap(fileName, flags);

                // Convert the image to bitmap
                if (bmp.ImageType != FREE_IMAGE_TYPE.FIT_BITMAP)
                {
                    bmp.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true);
                }

                return(bmp);
            }
            catch
            {
                throw;
//                return null;
            }
        }
Ejemplo n.º 2
0
        private static FIBITMAP complexedLoad(FileInfo inputFileInfo)
        {
            FIBITMAP              fibitmap           = FIBITMAP.Zero;
            FREE_IMAGE_FORMAT     freeImageFormat    = getComplexedFormat(FileUtil.getSuffix(inputFileInfo.Name));
            FREE_IMAGE_LOAD_FLAGS freeImageLoadFlags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;

            if (FREE_IMAGE_FORMAT.FIF_UNKNOWN != freeImageFormat)
            {
                fibitmap = FreeImage.Load(freeImageFormat, inputFileInfo.FullName, freeImageLoadFlags);
            }
            return(fibitmap);
        }
Ejemplo n.º 3
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.º 4
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);
         }
     }
 }
 /// <summary>
 /// Loads a .NET <see cref="System.Drawing.Bitmap"/> from a file.
 /// </summary>
 /// <param name="filename">Name of the file to be loaded.</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>The loaded .NET <see cref="System.Drawing.Bitmap"/>.</returns>
 /// <exception cref="FileNotFoundException">
 /// <paramref name="filename"/> does not exists.</exception>
 /// <exception cref="ArgumentException">
 /// The image type of the image is not <see cref="FREE_IMAGE_TYPE.FIT_BITMAP"/>.</exception>
 public static Bitmap LoadBitmap(string filename, FREE_IMAGE_LOAD_FLAGS flags, ref FREE_IMAGE_FORMAT format)
 {
     FIBITMAP dib = LoadEx(filename, flags, ref format);
     Bitmap result = GetBitmap(dib, true);
     Unload(dib);
     return result;
 }
    public RenderTexture LoadImage(string path, bool isLinear = false, bool isGrayscale = false, bool doMipMaps = false, bool forceGC = false, bool premultiplyAlpha = false)
    {
        // default bits per channel
        //uint origBPP = outBPP = 0;
        bool                successfullyLoadedRaw = false;
        int                 width = 0, height = 0;
        TextureFormat       formatToLoad = TextureFormat.ARGB32;
        RenderTextureFormat rtFormat = RenderTextureFormat.ARGB32;
        bool                forceGrayscaleAfterTexture2D = false;

        //System.Threading.Thread newThread = new System.Threading.Thread(() =>
        {
            var loadType = System.IO.Path.GetExtension(path);
            FREE_IMAGE_LOAD_FLAGS loadFlags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;
            switch (loadType)
            {
            case ".png":
                loadFlags = FREE_IMAGE_LOAD_FLAGS.PNG_IGNOREGAMMA;
                break;

            case ".jpg":
            case ".jpeg":
                loadFlags = FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE;
                break;
            }
            // Format is stored in 'format' on successfull load.
            FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
            FIBITMAP          dib;
            bool isModifiedEXR = false;
            char yChar         = 'Y';
            byte yByte         = Convert.ToByte(yChar);
            char rChar         = 'R';
            byte rByte         = Convert.ToByte(rChar);
            //byte[] byteArray = File.ReadAllBytes(path);
            FileStream stream = null;
            if (Path.GetExtension(path).ToLower() == ".exr")
            {
                stream = new FileStream(path, FileMode.Open);

                stream.Position = 66;
                isModifiedEXR   = (stream.ReadByte() == rByte);
                if (isModifiedEXR)
                {
                    Debug.Log("<color=blue>*** This is a modified EXR </color>");
                    //byteArray[66] = yByte;
                    stream.Position = 66;
                    stream.WriteByte(yByte);
                    stream.Position = 0;
                }
            }
#if UNITY_STANDALONE_OSX
            if (stream == null)
            {
                stream = new FileStream(path, FileMode.Open);
            }

            dib = FreeImage.LoadFromStream(stream, loadFlags, ref format);
#else
            dib = FreeImage.LoadEx(path, loadFlags, ref format);
            Debug.Log("Used Heap Size After FreeImage.LoadEx: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
#endif
            if (stream != null)
            {
                stream.Dispose();
                GC.Collect();
                Debug.Log("Used Heap Size After stream.Dispose: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
            }

            if (isModifiedEXR)
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    fs.Position = 66;
                    fs.WriteByte(rByte);
                    fs.Position = 0;
                }
            }
            rtFormat = RenderTextureFormat.ARGB32;
            try
            {
                // Error handling
                if (dib.IsNull)
                {
                    return(null);
                }

                FREE_IMAGE_TYPE origInputType = FreeImage.GetImageType(dib);

                //Debug.Log("DIB for :" + path);
                // read bits per channel of loaded image
                uint origBPP = FreeImage.GetBPP(dib);
                var  header  = FreeImage.GetInfoHeaderEx(dib);
                //Debug.Log("original BPP:" + origBPP);
                //Debug.Log("origInputType:" + origInputType);

                // check here if we need to convert single channel textures to RGB or vice versa based on source input texture type and destination type expected
                FREE_IMAGE_TYPE destType = FREE_IMAGE_TYPE.FIT_UNKNOWN;
                switch (origInputType)
                {
                case FREE_IMAGE_TYPE.FIT_UINT16:
                    if (!isGrayscale)
                    {
                        destType = FREE_IMAGE_TYPE.FIT_RGBAF;
                    }
                    else
                    {
                        destType = FREE_IMAGE_TYPE.FIT_FLOAT;
                    }
                    break;

                case FREE_IMAGE_TYPE.FIT_RGBF:
                case FREE_IMAGE_TYPE.FIT_RGBAF:
                    destType = isGrayscale ? FREE_IMAGE_TYPE.FIT_FLOAT : FREE_IMAGE_TYPE.FIT_RGBAF;
                    break;

                case FREE_IMAGE_TYPE.FIT_RGB16:
                case FREE_IMAGE_TYPE.FIT_RGBA16:
                    destType = isGrayscale ? FREE_IMAGE_TYPE.FIT_FLOAT : FREE_IMAGE_TYPE.FIT_RGBAF;
                    break;

                case FREE_IMAGE_TYPE.FIT_BITMAP:
                    if (isGrayscale)
                    {
                        if (Mathf.IsPowerOfTwo(header.biWidth) && Mathf.IsPowerOfTwo(header.biHeight))
                        {
                            if (!premultiplyAlpha)
                            {
                                dib = FreeImage.ConvertToGreyscale(dib);
                            }
                        }
                        else
                        {
                            //int w = Mathf.NextPowerOfTwo(header.biWidth);
                            //int h = Mathf.NextPowerOfTwo(header.biHeight);
                            //FIBITMAP bitmap2 = FreeImage.Allocate(w, h, 8);
                            //FreeImage.Paste(bitmap2, dib, 0, 0, 255);
                            //FreeImage.UnloadEx(ref dib);
                            //dib = bitmap2;

                            forceGrayscaleAfterTexture2D = true;
                            dib = FreeImage.ConvertTo32Bits(dib);
                        }
                    }
                    else
                    {
                        dib = FreeImage.ConvertTo32Bits(dib);
                    }
                    destType = FREE_IMAGE_TYPE.FIT_BITMAP;

                    break;
                }

                //// premultiply if need be
                //if (premultiplyAlpha)
                //    FreeImage.PreMultiplyWithAlpha(dib);

                // convert to destination expected type
                if (destType != FREE_IMAGE_TYPE.FIT_UNKNOWN && origInputType != destType)
                {
                    Debug.Log("Trying to convert from:" + origInputType + ", to:" + destType);
                    dib = FreeImage.ConvertToType(dib, destType, false);
                }
                //GC.Collect();
                Debug.Log("Used Heap Size After FreeImage.ConvertToType: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
                //if (isModifiedEXR && origInputType == FREE_IMAGE_TYPE.FIT_FLOAT)

                width  = (int)FreeImageAPI.FreeImage.GetWidth(dib);
                height = (int)FreeImageAPI.FreeImage.GetHeight(dib);
                uint bpp      = FreeImage.GetBPP(dib);
                int  pitch    = (int)FreeImage.GetPitch(dib);
                long byteSize = pitch * height;
                Debug.Log("byteSize: " + byteSize);
                FREE_IMAGE_TYPE inputType = FreeImage.GetImageType(dib);

                if (doMipMaps)
                {
                    byteSize = (long)(byteSize * 1.6666f);
                }

                //bytes = new byte[byteSize];
                FreeImage.ConvertToRawBits(bytes, dib, pitch, bpp, 0, 0, 0, false);

                Debug.Log("Used Heap Size After FreeImage.ConvertToRawBits: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);


                FreeImage.UnloadEx(ref dib);
                //GC.Collect();
                //Debug.Log("Used Heap Size After FreeImage.UnloadEx: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
                // choose texture format
                formatToLoad = TextureFormat.ARGB32;

                Debug.Log("inputType:" + inputType);
                switch (inputType)
                {
                case FREE_IMAGE_TYPE.FIT_FLOAT:
                    formatToLoad = TextureFormat.RFloat;
                    if (origInputType == FREE_IMAGE_TYPE.FIT_UINT16)
                    {
                        rtFormat = RenderTextureFormat.RHalf;
                    }
                    else
                    {
                        rtFormat = RenderTextureFormat.RFloat;
                    }
                    break;

                case FREE_IMAGE_TYPE.FIT_UINT16:
                    formatToLoad = TextureFormat.RHalf;
                    rtFormat     = RenderTextureFormat.RHalf;
                    break;

                case FREE_IMAGE_TYPE.FIT_RGBA16:
                    formatToLoad = TextureFormat.RGBAHalf;
                    rtFormat     = RenderTextureFormat.ARGBHalf;
                    isLinear     = true;
                    break;

                case FREE_IMAGE_TYPE.FIT_RGBAF:
                    formatToLoad = TextureFormat.RGBAFloat;

                    if (origInputType == FREE_IMAGE_TYPE.FIT_RGBA16 || origInputType == FREE_IMAGE_TYPE.FIT_RGB16)
                    {
                        rtFormat = RenderTextureFormat.ARGBHalf;
                    }
                    else
                    {
                        rtFormat = RenderTextureFormat.ARGBFloat;
                    }
                    isLinear = true;
                    break;

                case FREE_IMAGE_TYPE.FIT_BITMAP:
                    //Iterate over all scanlines

                    switch (bpp)
                    {
                    case 8:

                    {
                        formatToLoad = TextureFormat.Alpha8;
                        rtFormat     = RenderTextureFormat.R8;
                    }
                    break;

                    case 16:
                        formatToLoad = TextureFormat.RGBA4444;
                        rtFormat     = RenderTextureFormat.ARGB4444;
                        break;

                    case 24:
                        if (FreeImage.IsLittleEndian())
                        {
                            int length = bytes.Length;
                            // make sure it's a multiple of 3
                            int factor         = length / 3;
                            int adjustedLength = factor * 3;
                            // convert back to RGB
                            for (int i = 0; i < adjustedLength; i += 3)
                            {
                                // convert BGR to RGB
                                var r = bytes[i];
                                bytes[i]     = bytes[i + 2];
                                bytes[i + 2] = r;
                            }
                        }
                        formatToLoad = TextureFormat.RGB24;
                        rtFormat     = RenderTextureFormat.ARGB32;
                        break;

                    case 32:
                        if (forceGrayscaleAfterTexture2D)
                        {
                            formatToLoad = TextureFormat.ARGB32;
                            rtFormat     = RenderTextureFormat.R8;
                        }
                        else
                        {
                            if (FreeImage.IsLittleEndian())
                            {
                                int length = bytes.Length;
                                // make sure it's a multiple of 4
                                int factor         = length / 4;
                                int adjustedLength = factor * 4;
                                for (int j = 0; j < adjustedLength; j += 4)
                                {
                                    // convert BGRA to ARGB
                                    var a = bytes[j];
                                    var r = bytes[j + 1];
                                    bytes[j]     = bytes[j + 3];
                                    bytes[j + 1] = bytes[j + 2];
                                    bytes[j + 2] = r;
                                    bytes[j + 3] = a;
                                }
                            }
                            formatToLoad = TextureFormat.ARGB32;
                            rtFormat     = RenderTextureFormat.ARGB32;
                        }
                        break;
                    }
                    break;
                }
                successfullyLoadedRaw = true;
            }
            catch (System.Exception ex)
            {
                Debug.LogError("Exception: " + ex.Message);
            }
        }
        //);
        //newThread.IsBackground = true;
        //newThread.Start();
        //newThread.Join();
        //outBPP = origBPP;
        if (successfullyLoadedRaw)
        {
            RenderTexture temp = LoadRawToTexture2D(bytes, width, height, formatToLoad, rtFormat, doMipMaps, isLinear, forceGC, premultiplyAlpha);
            //GC.Collect();
            Debug.Log("Used Heap Size After LoadRawToTexture2D: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);

            return(temp);
        }
        return(null);
    }
        public static extern FIMULTIBITMAP OpenMultiBitmapFromHandle(FREE_IMAGE_FORMAT fif, ref FreeImageIO io,
			fi_handle handle, FREE_IMAGE_LOAD_FLAGS flags);
 public static extern FIMULTIBITMAP LoadMultiBitmapFromMemory(FREE_IMAGE_FORMAT fif, FIMEMORY stream, FREE_IMAGE_LOAD_FLAGS flags);
Ejemplo n.º 9
0
 private static extern FIBITMAP LoadFromMemoryLinux(FREE_IMAGE_FORMAT fif, FIMEMORY stream, FREE_IMAGE_LOAD_FLAGS flags);
Ejemplo n.º 10
0
 /// <summary>
 /// Loads a FreeImage multi-paged bitmap.
 /// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
 /// real format is being analysed. If no plugin can read the file, format remains
 /// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
 /// Load flags can be provided by the flags parameter.
 /// </summary>
 /// <param name="filename">The complete name of the file to load.</param>
 /// <param name="format">Format of the image. If the format is unknown use 
 /// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
 /// In case a suitable format was found by LoadEx it will be returned in format.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="create_new">When true a new bitmap is created.</param>
 /// <param name="read_only">When true the bitmap will be loaded read only.</param>
 /// <param name="keep_cache_in_memory">When true performance is increased at the cost of memory.</param>
 /// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
 /// <exception cref="FileNotFoundException">
 /// <paramref name="filename"/> does not exists while opening.</exception>
 public static FIMULTIBITMAP OpenMultiBitmapEx(
     string filename,
     ref FREE_IMAGE_FORMAT format,
     FREE_IMAGE_LOAD_FLAGS flags,
     bool create_new,
     bool read_only,
     bool keep_cache_in_memory)
 {
     if (!File.Exists(filename) && !create_new)
     {
         throw new FileNotFoundException(filename + " could not be found.");
     }
     if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
     {
         // Check if a plugin can read the data
         format = GetFileType(filename, 0);
     }
     FIMULTIBITMAP dib = 0;
     if (FIFSupportsReading(format))
     {
         dib = OpenMultiBitmap(format, filename, create_new, read_only, keep_cache_in_memory, flags);
     }
     return dib;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Loads a FreeImage multi-paged bitmap from a stream and returns the
        /// FreeImage memory stream used as temporary buffer.
        /// The bitmap can not be modified by calling
        /// <see cref="FreeImage.AppendPage(FIMULTIBITMAP,FIBITMAP)"/>,
        /// <see cref="FreeImage.InsertPage(FIMULTIBITMAP,Int32,FIBITMAP)"/>,
        /// <see cref="FreeImage.MovePage(FIMULTIBITMAP,Int32,Int32)"/> or
        /// <see cref="FreeImage.DeletePage(FIMULTIBITMAP,Int32)"/>.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="format">Format of the image.</param>
        /// <param name="flags">Flags to enable or disable plugin-features.</param>
        /// <param name="memory">The temporary memory buffer used to load the bitmap.</param>
        /// <returns>Handle to a FreeImage multi-paged bitmap.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="stream"/> is null.</exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="stream"/> can not read.</exception>
        public static FIMULTIBITMAP LoadMultiBitmapFromStream(
            Stream stream,
            FREE_IMAGE_FORMAT format,
            FREE_IMAGE_LOAD_FLAGS flags,
            out FIMEMORY memory)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (!stream.CanRead)
            {
                throw new ArgumentException("stream");
            }
            const int blockSize = 1024;
            int bytesRead;
            byte[] buffer = new byte[blockSize];

            stream = stream.CanSeek ? stream : new StreamWrapper(stream, true);
            memory = OpenMemory(IntPtr.Zero, 0);

            do
            {
                bytesRead = stream.Read(buffer, 0, blockSize);
                WriteMemory(buffer, (uint)blockSize, (uint)1, memory);
            }
            while (bytesRead == blockSize);

            return LoadMultiBitmapFromMemory(format, memory, flags);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Loads a FreeImage bitmap.
 /// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>
 /// the bitmaps real format is being analysed.
 /// The stream must be set to the correct position before calling LoadFromStream.
 /// </summary>
 /// <param name="stream">The stream to read from.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="format">Format of the image. If the format is unknown use
 /// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
 /// In case a suitable format was found by LoadFromStream it will be returned in format.</param>
 /// <returns>Handle to a FreeImage bitmap.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="stream"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="stream"/> is not capable of reading.</exception>
 public static FIBITMAP LoadFromStream(
     Stream stream,
     FREE_IMAGE_LOAD_FLAGS flags,
     ref FREE_IMAGE_FORMAT format)
 {
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     if (!stream.CanRead)
     {
         throw new ArgumentException("stream is not capable of reading.");
     }
     // Wrap the source stream if it is unable to seek (which is required by FreeImage)
     stream = (stream.CanSeek) ? stream : new StreamWrapper(stream, true);
     // Save the streams position
     if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
     {
         long position = stream.Position;
         // Get the format of the bitmap
         format = GetFileTypeFromStream(stream);
         // Restore the streams position
         stream.Position = position;
     }
     if (!FIFSupportsReading(format))
     {
         return 0;
     }
     // Create a 'FreeImageIO' structure for calling 'LoadFromHandle'
     // using the internal structure 'FreeImageStreamIO'.
     FreeImageIO io = FreeImageStreamIO.io;
     using (fi_handle handle = new fi_handle(stream))
     {
         return LoadFromHandle(format, ref io, handle, flags);
     }
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Loads a FreeImage bitmap.
 /// The stream must be set to the correct position before calling LoadFromStream.
 /// </summary>
 /// <param name="stream">The stream to read from.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Handle to a FreeImage bitmap.</returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="stream"/> is null.</exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="stream"/> is not capable of reading.</exception>
 public static FIBITMAP LoadFromStream(
     Stream stream,
     FREE_IMAGE_LOAD_FLAGS flags)
 {
     FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
     return LoadFromStream(stream, flags, ref format);
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Loads a FreeImage bitmap.
 /// In case the loading format is <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> the files
 /// real format is being analysed. If no plugin can read the file, format remains
 /// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/> and 0 is returned.
 /// Load flags can be provided by the flags parameter.
 /// </summary>
 /// <param name="filename">The complete name of the file to load.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <param name="format">Format of the image. If the format is unknown use
 /// <see cref="FREE_IMAGE_FORMAT.FIF_UNKNOWN"/>.
 /// In case a suitable format was found by LoadEx it will be returned in format.
 /// </param>
 /// <returns>Handle to a FreeImage bitmap.</returns>
 /// <exception cref="FileNotFoundException">
 /// <paramref name="filename"/> does not exists.</exception>
 public static FIBITMAP LoadEx(string filename, FREE_IMAGE_LOAD_FLAGS flags, ref FREE_IMAGE_FORMAT format)
 {
     // check if file exists
     if (!File.Exists(filename))
     {
         throw new FileNotFoundException(filename + " could not be found.");
     }
     FIBITMAP dib = 0;
     if (format == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
     {
         // query all plugins to see if one can read the file
         format = GetFileType(filename, 0);
     }
     // check if the plugin is capable of loading files
     if (FIFSupportsReading(format))
     {
         dib = Load(format, filename, flags);
     }
     return dib;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Loads a FreeImage bitmap.
 /// Load flags can be provided by the flags parameter.
 /// </summary>
 /// <param name="filename">The complete name of the file to load.</param>
 /// <param name="flags">Flags to enable or disable plugin-features.</param>
 /// <returns>Handle to a FreeImage bitmap.</returns>
 /// <exception cref="FileNotFoundException">
 /// <paramref name="filename"/> does not exists.</exception>
 public static FIBITMAP LoadEx(string filename, FREE_IMAGE_LOAD_FLAGS flags)
 {
     FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
     return LoadEx(filename, flags, ref format);
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Decodes the given stream, selects the correct page or frame, rotates it correctly (if autorotate=true), then executes the callback, then cleans up.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="settings"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static object DecodeAndCall(Stream s, ResizeSettings settings, DecodeCallback callback)
        {
            if (!FreeImageAPI.FreeImage.IsAvailable())
            {
                return(null);
            }

            FREE_IMAGE_LOAD_FLAGS flags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;

            //If we're not tone-mapping the raw file, convert it for display
            if (!HasToneMappingCommands(settings))
            {
                flags |= FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY;
            }

            bool usethumb = ("true".Equals(settings["usepreview"], StringComparison.OrdinalIgnoreCase));

            if (usethumb)
            {
                flags |= FREE_IMAGE_LOAD_FLAGS.RAW_PREVIEW;
            }

            bool autorotate = ("true".Equals(settings["autorotate"], StringComparison.OrdinalIgnoreCase));

            if (autorotate)
            {
                flags |= FREE_IMAGE_LOAD_FLAGS.JPEG_EXIFROTATE;
            }

            int page = 0;

            if (!string.IsNullOrEmpty(settings["page"]) && !int.TryParse(settings["page"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out page))
            {
                page = 0;
            }

            int frame = 0;

            if (!string.IsNullOrEmpty(settings["frame"]) && !int.TryParse(settings["frame"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out frame))
            {
                frame = 0;
            }

            if (page == 0 && frame != 0)
            {
                page = frame;
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            if (page > 1)
            {
                FREE_IMAGE_FORMAT fmt = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
                FIMULTIBITMAP     mb  = FreeImage.OpenMultiBitmapFromStream(s, ref fmt, flags);
                //Prevent asking for a non-existent page
                int pages = FreeImage.GetPageCount(mb);
                if (page > pages)
                {
                    page = pages;
                }
                try {
                    if (mb.IsNull)
                    {
                        return(null);
                    }
                    FIBITMAP bPage = FreeImage.LockPage(mb, page - 1);
                    if (bPage.IsNull)
                    {
                        return(null);
                    }
                    try {
                        sw.Stop();
                        return(ToneMap(ref bPage, false, settings, callback));
                    } finally {
                        FreeImage.UnlockPage(mb, bPage, false);
                    }
                } finally {
                    if (!mb.IsNull)
                    {
                        FreeImage.CloseMultiBitmapEx(ref mb, FREE_IMAGE_SAVE_FLAGS.DEFAULT);
                    }
                }
            }
            else
            {
                FIBITMAP original = FIBITMAP.Zero;
                try {
                    original = FreeImage.LoadFromStream(s, flags);
                    sw.Stop();
                    if (original.IsNull)
                    {
                        return(null);
                    }
                    return(ToneMap(ref original, true, settings, callback));
                } finally {
                    if (!original.IsNull)
                    {
                        FreeImage.UnloadEx(ref original);
                    }
                }
            }
        }
 public static extern FIBITMAP LoadFromHandle(FREE_IMAGE_FORMAT fif, ref FreeImageIO io, fi_handle handle, FREE_IMAGE_LOAD_FLAGS flags);
Ejemplo n.º 18
0
 private static extern FIMULTIBITMAP OpenMultiBitmapWindows(FREE_IMAGE_FORMAT fif, string filename, bool create_new, bool read_only, bool keep_cache_in_memory, FREE_IMAGE_LOAD_FLAGS flags);
        public static extern FIMULTIBITMAP OpenMultiBitmap(FREE_IMAGE_FORMAT fif, string filename, bool create_new,
			bool read_only, bool keep_cache_in_memory, FREE_IMAGE_LOAD_FLAGS flags);
Ejemplo n.º 20
0
 private static extern FIBITMAP LoadWindows(FREE_IMAGE_FORMAT fif, [MarshalAs(UnmanagedType.LPStr)] string filename, FREE_IMAGE_LOAD_FLAGS flags);
 private static extern FIBITMAP LoadU(FREE_IMAGE_FORMAT fif, string filename, FREE_IMAGE_LOAD_FLAGS flags);
Ejemplo n.º 22
0
 private static extern FIBITMAP LoadUWindows(FREE_IMAGE_FORMAT fif, string filename, FREE_IMAGE_LOAD_FLAGS flags);
    //public Texture2D tex;

    public byte[] LoadImageBytes(string path, bool isLinear = false, bool isGrayscale = false, bool doMipMaps = false, bool forceGC = false, bool premultiplyAlpha = false)
    {
        // default bits per channel
        //uint origBPP = outBPP = 0;
        bool                successfullyLoadedRaw = false;
        int                 width = 0, height = 0;
        TextureFormat       formatToLoad = TextureFormat.ARGB32;
        RenderTextureFormat rtFormat = RenderTextureFormat.ARGB32;
        bool                forceGrayscaleAfterTexture2D = false;

        var loadType = System.IO.Path.GetExtension(path);
        FREE_IMAGE_LOAD_FLAGS loadFlags = FREE_IMAGE_LOAD_FLAGS.DEFAULT;

        switch (loadType)
        {
        case ".png":
            loadFlags = FREE_IMAGE_LOAD_FLAGS.PNG_IGNOREGAMMA;
            break;

        case ".jpg":
        case ".jpeg":
            loadFlags = FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE;
            break;
        }
        // Format is stored in 'format' on successfull load.
        FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
        FIBITMAP          dib;
        bool isModifiedEXR = false;
        char yChar         = 'Y';
        byte yByte         = Convert.ToByte(yChar);
        char rChar         = 'R';
        byte rByte         = Convert.ToByte(rChar);
        //byte[] byteArray = File.ReadAllBytes(path);
        FileStream stream = null;

        if (Path.GetExtension(path).ToLower() == ".exr")
        {
            stream = new FileStream(path, FileMode.Open);

            stream.Position = 66;
            isModifiedEXR   = (stream.ReadByte() == rByte);
            if (isModifiedEXR)
            {
                Debug.Log("<color=blue>*** This is a modified EXR </color>");
                //byteArray[66] = yByte;
                stream.Position = 66;
                stream.WriteByte(yByte);
                stream.Position = 0;
            }
        }

#if UNITY_STANDALONE_OSX
        if (stream == null)
        {
            stream = new FileStream(path, FileMode.Open);
        }

        dib = FreeImage.LoadFromStream(stream, loadFlags, ref format);
#else
        dib = FreeImage.LoadEx(path, loadFlags, ref format);
        Debug.Log("Used Heap Size After FreeImage.LoadEx: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
#endif
        if (stream != null)
        {
            stream.Dispose();
            GC.Collect();
            Debug.Log("Used Heap Size After stream.Dispose: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024);
        }
        width  = (int)FreeImageAPI.FreeImage.GetWidth(dib);
        height = (int)FreeImageAPI.FreeImage.GetHeight(dib);
        uint bpp      = FreeImage.GetBPP(dib);
        int  pitch    = (int)FreeImage.GetPitch(dib);
        long byteSize = pitch * height;
        Debug.Log("width: " + width + ", height: " + height + ", bpp: " + bpp + ", pitch: " + pitch + "byteSize: " + byteSize);

        if (doMipMaps)
        {
            byteSize = (long)(byteSize * 1.6666f);
        }


        FreeImage.ConvertToRawBits(bytes, dib, pitch, bpp, 0, 0, 0, false);

        FreeImage.UnloadEx(ref dib);

        return(bytes);
    }
Ejemplo n.º 24
0
 private static extern FIMULTIBITMAP LoadMultiBitmapFromMemoryWindows(FREE_IMAGE_FORMAT fif, FIMEMORY stream, FREE_IMAGE_LOAD_FLAGS flags);