Esempio n. 1
0
        private static int GetTextureSize(GifInfo frameInfo, int i)
        {
            int testNum = 2;

retry:
            int numFrames = frameInfo.frameCount;

            // Make sure the number of frames is cleanly divisible by our testNum
            if (!(numFrames % testNum != 0))
            {
                numFrames += numFrames % testNum;
            }

            int numFramesInRow    = numFrames / testNum;
            int numFramesInColumn = numFrames / numFramesInRow;

            if (numFramesInRow > numFramesInColumn)
            {
                testNum += 2;
                goto retry;
            }

            var textureWidth  = Mathf.Clamp(numFramesInRow * frameInfo.frames[i].width, 0, 2048);
            var textureHeight = Mathf.Clamp(numFramesInColumn * frameInfo.frames[i].height, 0, 2048);

            return(Mathf.Max(textureWidth, textureHeight));
        }
Esempio n. 2
0
        private static void ProcessingThread(byte[] gifData, GifInfo frameInfo)
        {
            var gifImage   = EmojiUtilities.byteArrayToImage(gifData);
            var dimension  = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
            int frameCount = gifImage.GetFrameCount(dimension);

            frameInfo.frameCount  = frameCount;
            frameInfo.initialized = true;

            int index           = 0;
            int firstDelayValue = -1;

            for (int i = 0; i < frameCount; i++)
            {
                gifImage.SelectActiveFrame(dimension, i);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(gifImage.Width, gifImage.Height);
                System.Drawing.Graphics.FromImage(bitmap).DrawImage(gifImage, System.Drawing.Point.Empty);
                LockBitmap frame = new LockBitmap(bitmap);
                frame.LockBits();
                FrameInfo currentFrame = new FrameInfo(bitmap.Width, bitmap.Height);

                if (currentFrame.colors == null)
                {
                    currentFrame.colors = new Color32[frame.Height * frame.Width];
                }
                for (int x = 0; x < frame.Width; x++)
                {
                    for (int y = 0; y < frame.Height; y++)
                    {
                        System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                        currentFrame.colors[(frame.Height - y - 1) * frame.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A);
                    }
                }

                int delayPropertyValue = BitConverter.ToInt32(gifImage.GetPropertyItem(20736).Value, index);
                if (firstDelayValue == -1)
                {
                    firstDelayValue = delayPropertyValue;
                }

                if (delayPropertyValue != firstDelayValue)
                {
                    frameInfo.isDelayConsistent = false;
                }

                currentFrame.delay = delayPropertyValue * 10;
                frameInfo.frames.Add(currentFrame);
                index += 4;

                Thread.Sleep(Globals.IsAtMainMenu ? 0 : 10);
            }
        }
Esempio n. 3
0
        private static void ProcessingThread(byte[] gifData, GifInfo frameInfo)
        {
            var gifImage   = EmojiUtilities.byteArrayToImage(gifData);
            var dimension  = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
            int frameCount = gifImage.GetFrameCount(dimension);

            frameInfo.frameCount  = frameCount;
            frameInfo.dimension   = dimension;
            frameInfo.initialized = true;

            int index = 0;

            for (int i = 0; i < frameCount; i++)
            {
                gifImage.SelectActiveFrame(dimension, i);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(gifImage.Width, gifImage.Height);
                System.Drawing.Graphics.FromImage(bitmap).DrawImage(gifImage, System.Drawing.Point.Empty);
                LockBitmap frame = new LockBitmap(bitmap);

                frame.LockBits();
                FrameInfo currentFrame = new FrameInfo(bitmap.Width, bitmap.Height);

                if (currentFrame.colors == null)
                {
                    currentFrame.colors = new Color32[frame.Height * frame.Width];
                }

                for (int x = 0; x < frame.Width; x++)
                {
                    for (int y = 0; y < frame.Height; y++)
                    {
                        System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                        currentFrame.colors[(frame.Height - y - 1) * frame.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A);
                    }
                }

                int delayPropertyValue = BitConverter.ToInt32(gifImage.GetPropertyItem(20736).Value, index);
                // If the delay property is 0, assume that it's a 10fps emote
                if (delayPropertyValue == 0)
                {
                    delayPropertyValue = 10;
                }

                currentFrame.delay = (float)delayPropertyValue / 100.0f;
                frameInfo.frames.Add(currentFrame);
                index += 4;

                Thread.Sleep(0);
            }
        }
Esempio n. 4
0
    public GifInfo DecodeGIFTask(byte[] b)
    {
        Debug.Log("Started decoding gif...");
        DateTime startTime = DateTime.Now;

        Image          gifImage   = Image.FromStream(new MemoryStream(b));
        FrameDimension dimension  = new FrameDimension(gifImage.FrameDimensionsList[0]);
        int            frameCount = gifImage.GetFrameCount(dimension);

        GifInfo gifInfo = new GifInfo(frameCount);

        int index = -4;

        for (int i = 0; i < frameCount; ++i)
        {
            gifImage.SelectActiveFrame(dimension, i);
            Bitmap bitmap = new Bitmap(gifImage.Width, gifImage.Height);
            System.Drawing.Graphics.FromImage(bitmap).DrawImage(gifImage, Point.Empty);

            FrameInfo frameInfo = new FrameInfo();

            frameInfo.width  = bitmap.Width;
            frameInfo.height = bitmap.Height;
            frameInfo.delay  = BitConverter.ToInt16(gifImage.GetPropertyItem(20736).Value, index += 4) * 10; //Get frame delay value

            LockBitmap lockBitmap = new LockBitmap(bitmap);
            lockBitmap.LockBits();

            frameInfo.colors = new Color32[lockBitmap.Height * lockBitmap.Width];

            for (int x = 0; x < lockBitmap.Width; ++x)
            {
                for (int y = 0; y < lockBitmap.Height; ++y)
                {
                    System.Drawing.Color sourceColor = lockBitmap.GetPixel(x, y);
                    frameInfo.colors[(lockBitmap.Height - y - 1) * lockBitmap.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A);
                }
            }

            gifInfo.frames[i] = frameInfo;
        }

        Debug.Log("Finished decoding GIF. Elapsed time: " + (DateTime.Now - startTime).TotalSeconds + " seconds.");

        return(gifInfo);
    }
Esempio n. 5
0
 private static void SaveGifInfo(GifInfo info, string sSavePath, string sCompress)
 {
     sSavePath = Path.GetDirectoryName(sSavePath) + "\\" + Path.GetFileNameWithoutExtension(sSavePath) + ".ini";
     using (var streamWriter = new StreamWriter(sSavePath))
     {
         streamWriter.WriteLine("[Info]");
         streamWriter.WriteLine("Depth=" + _sSourcePath);
         streamWriter.WriteLine("Source=" + _sSourcePath);
         streamWriter.WriteLine("Count=" + (info.nCount + 1));
         streamWriter.WriteLine("Compress=" + sCompress);
         streamWriter.WriteLine("Depth=" + _depth);
         for (var index = 0; index < info.lstDelay.Count; ++index)
         {
             streamWriter.WriteLine("Delay" + index + "=" + info.lstDelay[index]);
         }
     }
 }
Esempio n. 6
0
    public IEnumerator ProcessGif(byte[] b)
    {
        GifInfo gifInfo = null;

        //Debug.Log("Gif decode task started");

        Task.Run(() => gifInfo = DecodeGIFTask(b));         //Start decoding gif
        yield return(new WaitUntil(() => gifInfo != null)); //Wait for decoding to finish

        //Debug.Log("Gif decode task completed");

        Gif gif = new Gif(gifInfo.frameCount);

        Texture2D[] textures = new Texture2D[gifInfo.frameCount];

        for (int i = 0; i < gifInfo.frameCount; ++i)
        {
            FrameInfo currentFrameInfo = gifInfo.frames[i];

            Texture2D frameTexture = new Texture2D(currentFrameInfo.width, currentFrameInfo.height, TextureFormat.RGBA32, false);

            frameTexture.SetPixels32(currentFrameInfo.colors);
            frameTexture.Apply();

            textures[i]   = frameTexture;
            gif.delays[i] = currentFrameInfo.delay;

            yield return(null);
        }

        int       textureSize = 4096;
        Texture2D packTexture = new Texture2D(textureSize, textureSize);

        gif.atlas         = packTexture.PackTextures(textures, 2, textureSize, true);
        gif.packedTexture = packTexture;

        //Play the animation
        example.PlayMaterialAnimation(gif);
    }
Esempio n. 7
0
        public static ImageDataList GetImageDataList(string gifFileName)
        {
            ImageDataList imageDatas = new ImageDataList();

#if XBOX360 || SILVERLIGHT
            if (gifFileName.StartsWith(@".\") || gifFileName.StartsWith(@"./"))
            {
                gifFileName = gifFileName.Substring(2);
            }
#endif

#if SILVERLIGHT || WINDOWS_8
            using (Stream stream = FileManager.GetStreamForFile(gifFileName))
#else
            using (FileStream stream = System.IO.File.OpenRead(gifFileName))
#endif

            {
                mGifInfo = new GifInfo();
                mGifInfo.DelayTimes = new List<short>();

                BinaryReader reader = new BinaryReader(stream);

                #region header
                // Example:  GIF89a
                byte[] buffer = reader.ReadBytes(6);
                // set the header here
                char[] charArray = new char[buffer.Length];
                for (int i = 0; i < buffer.Length; i++)
                {
                    charArray[i] = (char)buffer[i];
                }

                mGifInfo.Header = new string(charArray);
                #endregion

                #region Width/Height

                mGifInfo.Width = reader.ReadInt16();
                mGifInfo.Height = reader.ReadInt16();

                #endregion

                #region Packed information

                // The packed byte has the following info:
                // Bits 0-2     Size of the Global Color Table
                // Bit 3        Color Table Sort Flag
                // Bits 4-6     Color Resolution
                // Bit 7        Global Color Table Flag

                Byte packedByte = reader.ReadByte();

                int sizeOfGlobalColorTable = (7 & packedByte);

                mGifInfo.NumberOfColorEntries = 1 * (1 << (sizeOfGlobalColorTable + 1));

                mGifInfo.HasGlobalColorTable = (128 & packedByte) != 0;

                #endregion

                #region background color
                reader.ReadByte();
                #endregion

                #region default aspect ratio

                reader.ReadByte();

                #endregion

                TryReadGlobalColorTable(reader);


                byte separator = reader.ReadByte();

                while (separator != 0x3b) // Extension
                {
                    switch(separator)
                    {
                        #region Extensions

                        case 0x21:

                            Byte label = reader.ReadByte();

                            switch (label)
                            {
                                case 0xf9:
                                    ReadGraphicsControlExtension(reader);
                                    break;
                                case 0xff:
                                    ReadApplicationExtensionBlock(reader);
                                    break;
                                case 0xfe:
                                    ReadCommonExtensionBlock(reader);
                                    break;

                            }
                            break;
                        #endregion

                        #region Image Data
                        case 0x2c:

                            ReadImageDescriptor(reader);


                            Color[] color = new Color[mGifInfo.Width * mGifInfo.Height];

                            int transparentIndex = mGifInfo.TransparentIndex;

                            #region Interlaced
                            if (mGifInfo.IsInterlaced)
                            {
                                int i = 0;
                                for (int pass = 0; pass < 4; ++pass)
                                {
                                    int row = 0;
                                    int increment = 0;

                                    switch (pass)
                                    {
                                        case 0: row = 0; increment = 8; break;
                                        case 1: row = 4; increment = 8; break;
                                        case 2: row = 2; increment = 4; break;
                                        case 3: row = 1; increment = 2; break;
                                    }
                                    for (; row < mGifInfo.Height; row += increment)
                                    {

                                        for (int col = 0; col < mGifInfo.Width; ++col)
                                        {
                                            int position = (row * mGifInfo.Width) + col;

                                            byte index = mUncompressedColorIndexBuffer[i++];

                                            byte alpha = 255;

                                            if (mGifInfo.HasTransparency && index == transparentIndex)
                                                alpha = 0;

#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
                                        color[position] = new Color(
                                            (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].B,
                                            (byte)alpha);
#elif FRB_MDX
                                            color[position] = Color.FromArgb(
                                                alpha,
                                                (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                                (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                                (byte)mGifInfo.PaletteInfo.Entries[index].B);

#endif

                                        }

                                    }

                                }
                            }
                            #endregion
                            else
                            {
                                #region NonInterlaced

                                for (int i = 0; i < mGifInfo.PaletteInfo.Entries.Length; i++)
                                {
                                    mGifInfo.PaletteInfo.Entries[transparentIndex].A = 255;
                                }                                
                                if (mGifInfo.HasTransparency)
                                {
                                    mGifInfo.PaletteInfo.Entries[transparentIndex].A = 0;
                                }

                                int x = 0;
                                int y = 0;

                                int colorIndex;

                                for (int i = 0; i < mUncompressedColorIndexBuffer.Count; i++)
                                {                                    
                                    byte index = mUncompressedColorIndexBuffer[i];

                                    // Let's see if we can avoid an if statement
                                    x = mGifInfo.CurrentBlockLeft + i % mGifInfo.CurrentBlockWidth;
                                    y = mGifInfo.CurrentBlockTop + i / mGifInfo.CurrentBlockWidth;

                                    colorIndex = x + y * mGifInfo.Width;

#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
                                    color[colorIndex] = new Color(
                                        (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].B,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].A);
#elif FRB_MDX
                                    color[colorIndex] = Color.FromArgb(
                                        (byte)mGifInfo.PaletteInfo.Entries[index].A,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                        (byte)mGifInfo.PaletteInfo.Entries[index].B);
#endif
                                }
                                #endregion
                            }
                            ImageData imageData = new ImageData(
                                mGifInfo.Width, mGifInfo.Height, color);

                            imageDatas.Add(imageData);

                            mUncompressedColorIndexBuffer.Clear();

                            break;
                        #endregion

                        #region End of file
                        case 0x3b:

                            // end of file
                            break;

                        #endregion
                    }

                    separator = reader.ReadByte();
                }
            }

            // Fill the imageDatas with the frame times
            foreach (short s in mGifInfo.DelayTimes)
            {
                imageDatas.FrameTimes.Add(s / 100.0);
            }

            return imageDatas;
        }
Esempio n. 8
0
        public static IEnumerator Process(byte[] gifData, Action <Texture2D, Rect[], float[], bool, int, int, TextureDownloadInfo> callback, TextureDownloadInfo imageDownloadInfo)
        {
            Plugin.Log($"Started decoding gif {imageDownloadInfo.spriteIndex}");

            List <Texture2D> texList   = new List <Texture2D>();
            GifInfo          frameInfo = new GifInfo();
            DateTime         startTime = DateTime.Now;

            Task.Run(() => ProcessingThread(gifData, frameInfo));
            yield return(new WaitUntil(() => { return frameInfo.initialized; }));


            int          textureSize = 2048, width = 0, height = 0;
            Texture2D    texture = null;
            List <float> delays  = new List <float>();

            for (int i = 0; i < frameInfo.frameCount; i++)
            {
                if (frameInfo.frames.Count <= i)
                {
                    yield return(new WaitUntil(() => { return frameInfo.frames.Count > i; }));
                    //Plugin.Log($"Frame {i} is ready for processing! Frame is {frameInfo.frames[i].width}x{frameInfo.frames[i].height}");
                }

                if (texture == null)
                {
                    textureSize = GetTextureSize(frameInfo, i);
                    texture     = new Texture2D(textureSize, textureSize);
                }

                FrameInfo currentFrameInfo = frameInfo.frames[i];
                delays.Add(currentFrameInfo.delay);

                var frameTexture = new Texture2D(currentFrameInfo.width, currentFrameInfo.height, TextureFormat.RGBA32, false);
                frameTexture.wrapMode = TextureWrapMode.Clamp;
                try
                {
                    frameTexture.SetPixels32(currentFrameInfo.colors);
                    frameTexture.Apply(i == 0);
                }
                catch (Exception e)
                {
                    Plugin.Log($"Exception while decoding gif! Frame: {i}, Exception: {e}");
                    yield break;
                }
                yield return(null);

                texList.Add(frameTexture);

                // Instant callback after we decode the first frame in order to display a still image until the animated one is finished loading
                if (i == 0)
                {
                    width  = frameInfo.frames[i].width;
                    height = frameInfo.frames[i].height;
                    callback?.Invoke(frameTexture, texture.PackTextures(new Texture2D[] { frameTexture }, 2, textureSize, true), delays.ToArray(), true, width, height, imageDownloadInfo);
                }
            }
            Rect[] atlas = texture.PackTextures(texList.ToArray(), 2, textureSize, true);

            yield return(null);

            callback?.Invoke(texture, atlas, delays.ToArray(), frameInfo.isDelayConsistent, width, height, imageDownloadInfo);
            Plugin.Log($"Finished decoding gif {imageDownloadInfo.spriteIndex}! Elapsed time: {(DateTime.Now - startTime).TotalSeconds} seconds.");
        }
Esempio n. 9
0
        public static ImageDataList GetImageDataList(string gifFileName)
        {
            ImageDataList imageDatas = new ImageDataList();

#if XBOX360 || SILVERLIGHT
            if (gifFileName.StartsWith(@".\") || gifFileName.StartsWith(@"./"))
            {
                gifFileName = gifFileName.Substring(2);
            }
#endif

#if SILVERLIGHT || WINDOWS_8
            using (Stream stream = FileManager.GetStreamForFile(gifFileName))
#else
            using (FileStream stream = System.IO.File.OpenRead(gifFileName))
#endif

            {
                mGifInfo            = new GifInfo();
                mGifInfo.DelayTimes = new List <short>();

                BinaryReader reader = new BinaryReader(stream);

                #region header
                // Example:  GIF89a
                byte[] buffer = reader.ReadBytes(6);
                // set the header here
                char[] charArray = new char[buffer.Length];
                for (int i = 0; i < buffer.Length; i++)
                {
                    charArray[i] = (char)buffer[i];
                }

                mGifInfo.Header = new string(charArray);
                #endregion

                #region Width/Height

                mGifInfo.Width  = reader.ReadInt16();
                mGifInfo.Height = reader.ReadInt16();

                #endregion

                #region Packed information

                // The packed byte has the following info:
                // Bits 0-2     Size of the Global Color Table
                // Bit 3        Color Table Sort Flag
                // Bits 4-6     Color Resolution
                // Bit 7        Global Color Table Flag

                Byte packedByte = reader.ReadByte();

                int sizeOfGlobalColorTable = (7 & packedByte);

                mGifInfo.NumberOfColorEntries = 1 * (1 << (sizeOfGlobalColorTable + 1));

                mGifInfo.HasGlobalColorTable = (128 & packedByte) != 0;

                #endregion

                #region background color
                reader.ReadByte();
                #endregion

                #region default aspect ratio

                reader.ReadByte();

                #endregion

                TryReadGlobalColorTable(reader);


                byte separator = reader.ReadByte();

                while (separator != 0x3b) // Extension
                {
                    switch (separator)
                    {
                        #region Extensions

                    case 0x21:

                        Byte label = reader.ReadByte();

                        switch (label)
                        {
                        case 0xf9:
                            ReadGraphicsControlExtension(reader);
                            break;

                        case 0xff:
                            ReadApplicationExtensionBlock(reader);
                            break;

                        case 0xfe:
                            ReadCommonExtensionBlock(reader);
                            break;
                        }
                        break;
                        #endregion

                        #region Image Data
                    case 0x2c:

                        ReadImageDescriptor(reader);


                        Color[] color = new Color[mGifInfo.Width * mGifInfo.Height];

                        int transparentIndex = mGifInfo.TransparentIndex;

                        #region Interlaced
                        if (mGifInfo.IsInterlaced)
                        {
                            int i = 0;
                            for (int pass = 0; pass < 4; ++pass)
                            {
                                int row       = 0;
                                int increment = 0;

                                switch (pass)
                                {
                                case 0: row = 0; increment = 8; break;

                                case 1: row = 4; increment = 8; break;

                                case 2: row = 2; increment = 4; break;

                                case 3: row = 1; increment = 2; break;
                                }
                                for (; row < mGifInfo.Height; row += increment)
                                {
                                    for (int col = 0; col < mGifInfo.Width; ++col)
                                    {
                                        int position = (row * mGifInfo.Width) + col;

                                        byte index = mUncompressedColorIndexBuffer[i++];

                                        byte alpha = 255;

                                        if (mGifInfo.HasTransparency && index == transparentIndex)
                                        {
                                            alpha = 0;
                                        }

#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
                                        color[position] = new Color(
                                            (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].B,
                                            (byte)alpha);
#elif FRB_MDX
                                        color[position] = Color.FromArgb(
                                            alpha,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                            (byte)mGifInfo.PaletteInfo.Entries[index].B);
#endif
                                    }
                                }
                            }
                        }
                        #endregion
                        else
                        {
                            #region NonInterlaced

                            for (int i = 0; i < mGifInfo.PaletteInfo.Entries.Length; i++)
                            {
                                mGifInfo.PaletteInfo.Entries[transparentIndex].A = 255;
                            }
                            if (mGifInfo.HasTransparency)
                            {
                                mGifInfo.PaletteInfo.Entries[transparentIndex].A = 0;
                            }

                            int x = 0;
                            int y = 0;

                            int colorIndex;

                            for (int i = 0; i < mUncompressedColorIndexBuffer.Count; i++)
                            {
                                byte index = mUncompressedColorIndexBuffer[i];

                                // Let's see if we can avoid an if statement
                                x = mGifInfo.CurrentBlockLeft + i % mGifInfo.CurrentBlockWidth;
                                y = mGifInfo.CurrentBlockTop + i / mGifInfo.CurrentBlockWidth;

                                colorIndex = x + y * mGifInfo.Width;

#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
                                color[colorIndex] = new Color(
                                    (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].B,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].A);
#elif FRB_MDX
                                color[colorIndex] = Color.FromArgb(
                                    (byte)mGifInfo.PaletteInfo.Entries[index].A,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].R,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].G,
                                    (byte)mGifInfo.PaletteInfo.Entries[index].B);
#endif
                            }
                            #endregion
                        }
                        ImageData imageData = new ImageData(
                            mGifInfo.Width, mGifInfo.Height, color);

                        imageDatas.Add(imageData);

                        mUncompressedColorIndexBuffer.Clear();

                        break;
                        #endregion

                        #region End of file
                    case 0x3b:

                        // end of file
                        break;

                        #endregion
                    }

                    separator = reader.ReadByte();
                }
            }

            // Fill the imageDatas with the frame times
            foreach (short s in mGifInfo.DelayTimes)
            {
                imageDatas.FrameTimes.Add(s / 100.0);
            }

            return(imageDatas);
        }
Esempio n. 10
0
        public static IEnumerator Process(byte[] gifData, Action <Texture2D, Rect[], float, TextureDownloadInfo> callback, TextureDownloadInfo imageDownloadInfo)
        {
            Plugin.Log($"Started decoding gif {imageDownloadInfo.spriteIndex}");

            List <Texture2D> texList   = new List <Texture2D>();
            GifInfo          frameInfo = new GifInfo();
            DateTime         startTime = DateTime.Now;

            Task.Run(() => ProcessingThread(gifData, ref frameInfo));
            yield return(new WaitUntil(() => { return frameInfo.initialized; }));


            int       textureSize = 2048;
            Texture2D texture     = null;
            float     delay       = -1f;

            for (int i = 0; i < frameInfo.frameCount; i++)
            {
                yield return(new WaitUntil(() => { return frameInfo.frames.Count > i; }));

                //Plugin.Log($"Frame {i} is ready for processing! Frame is {frameInfo.frames[i].frame.Width}x{frameInfo.frames[i].frame.Height}");

                if (texture == null)
                {
                    textureSize = GetTextureSize(frameInfo, i);
                    texture     = new Texture2D(textureSize, textureSize);
                }

                FrameInfo currentFrameInfo = frameInfo.frames[i];
                if (delay == -1f)
                {
                    delay = currentFrameInfo.delay;
                }

                var frameTexture = new Texture2D(currentFrameInfo.frame.Width, currentFrameInfo.frame.Height);
                try
                {
                    int       colorIndex = 0;
                    Color32[] colors     = new Color32[currentFrameInfo.frame.Width * currentFrameInfo.frame.Height];
                    for (int x = 0; x < currentFrameInfo.frame.Width; x++)
                    {
                        for (int y = 0; y < currentFrameInfo.frame.Height; y++)
                        {
                            System.Drawing.Color sourceColor = currentFrameInfo.colors[colorIndex];
                            colors[(currentFrameInfo.frame.Height - y - 1) * currentFrameInfo.frame.Width + x] = new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A);
                            colorIndex++;
                        }
                    }
                    frameTexture.wrapMode = TextureWrapMode.Clamp;
                    frameTexture.SetPixels32(colors);
                    frameTexture.Apply(i == 0);
                }
                catch (Exception e)
                {
                    Plugin.Log($"Exception while decoding gif! Frame: {i}, Exception: {e}");
                    yield break;
                }
                yield return(null);

                texList.Add(frameTexture);

                // Instant callback after we decode the first frame in order to display a still image until the animated one is finished loading
                if (i == 0)
                {
                    callback?.Invoke(frameTexture, texture.PackTextures(new Texture2D[] { frameTexture }, 2, textureSize, true), delay, imageDownloadInfo);
                }
            }
            Rect[] atlas = texture.PackTextures(texList.ToArray(), 2, textureSize, true);

            yield return(null);

            callback?.Invoke(texture, atlas, delay, imageDownloadInfo);
            Plugin.Log($"Finished decoding gif {imageDownloadInfo.spriteIndex}! Elapsed time: {(DateTime.Now - startTime).TotalSeconds} seconds.");
        }
Esempio n. 11
0
        private static GifInfo ChangeGif(Image img, int targetWidth, int targetHeight, int sourceX, int sourceY,
                                         int sourceWidth, int sourceHeight,
                                         string savePath, int nDepth, string sCompress)
        {
            var newImage  = (Image) new Bitmap(targetWidth, targetHeight);
            var graphics1 = Graphics.FromImage(newImage);
            var gifInfo   = new GifInfo();
            var bmps      = new List <Bitmap>();

            foreach (var frameDimensions in img.FrameDimensionsList)
            {
                var dimension  = new FrameDimension(frameDimensions);
                var time       = FrameDimension.Time;
                var frameCount = img.GetFrameCount(dimension);
                var encoder    = GetEncoder(ImageFormat.Gif);
                var saveFlag   = Encoder.SaveFlag;
                gifInfo.nCount   = frameCount;
                gifInfo.lstDelay = new List <int>();
                for (var index = 0; index < frameCount; ++index)
                {
                    img.SelectActiveFrame(time, index);
                    gifInfo.lstDelay.Add(GetGifDelay(img, index));
                    var image2    = (Image) new Bitmap(targetWidth, targetHeight, _sDpp);
                    var graphics2 = Graphics.FromImage(image2);
                    graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics2.DrawImage(img, new Rectangle(0, 0, targetWidth, targetHeight),
                                        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                                        GraphicsUnit.Pixel);
                    if (nDepth > 0)
                    {
                        image2 = LightenMargin((Bitmap)image2, nDepth);
                    }
                    image2.Save(GetPathByExt(savePath, "bmp"), ImageFormat.Bmp);
                    if (index == 0)
                    {
                        bmps.Add((Bitmap)image2.Clone());
                    }
                    bmps.Add((Bitmap)image2);
                    long num = 21;
                    if (index == 0)
                    {
                        image2.Save(GetPathByExt(savePath, "bak.bmp"), ImageFormat.Bmp);
                        image2.Save(GetPathByExt(savePath, "bmp"), ImageFormat.Bmp);
                        graphics1.DrawImage(img, new Rectangle(0, 0, targetWidth, targetHeight),
                                            new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                                            GraphicsUnit.Pixel);
                        num = 18L;
                        bindProperty(img, newImage);
                    }

                    var encoderParams = new EncoderParameters(2);
                    encoderParams.Param[0] = new EncoderParameter(saveFlag, num);
                    encoderParams.Param[1] = new EncoderParameter(Encoder.ScanMethod, 8);
                    if (index == 0)
                    {
                        newImage.Save(GetPathByExt(savePath, "bak.gif"), encoder, encoderParams);
                    }
                    else
                    {
                        newImage.SaveAdd(image2, encoderParams);
                    }
                    graphics2.Dispose();
                }

                var encoderParams1 = new EncoderParameters(2);
                encoderParams1.Param[0] = new EncoderParameter(saveFlag, 20L);
                encoderParams1.Param[1] = new EncoderParameter(Encoder.ScanMethod, 8);
                newImage.SaveAdd(encoderParams1);
            }

            img.Dispose();
            File.Copy(GetPathByExt(savePath, "bak.gif"), GetPathByExt(savePath, "gif"), true);
            SaveZipData(savePath, sCompress, bmps);
            return(gifInfo);
        }