Beispiel #1
0
        Image[] getFrames(Image originalImg)
        {
            int            numberOfFrames;
            FrameDimension TargetDimension;

            try
            {
                numberOfFrames  = originalImg.GetFrameCount(FrameDimension.Time);
                TargetDimension = FrameDimension.Time;
            }
            catch
            {
                numberOfFrames  = originalImg.GetFrameCount(FrameDimension.Page);
                TargetDimension = FrameDimension.Page;
            }

            Image[] frames = new Image[numberOfFrames];

            for (int i = 0; i < numberOfFrames; i++)
            {
                originalImg.SelectActiveFrame(TargetDimension, i);
                frames[i] = ((Image)originalImg.Clone());
            }

            return(frames);
        }
        public static Gif ImageToGif(Image i)
        {
            FrameDimension dimension = new FrameDimension(i.FrameDimensionsList[0]);

            int[] timings = new int[i.GetFrameCount(dimension)];
            return(new Gif(Enumerable.Range(0, i.GetFrameCount(dimension)).
                           Select(x =>
            {
                i.SelectActiveFrame(dimension, x);
                try
                {
                    timings[x] = BitConverter.ToInt32(i.GetPropertyItem(20736).Value, x * 4) * 10;     // this works on windows sometimes
                }
                catch
                {
                    try
                    {
                        var prop = i.GetPropertyItem(20736);
                        timings[x] = (prop.Value[0] + prop.Value[1] * 256) * 10;     // this works according to https://stackoverflow.com/questions/3785031/getting-the-frame-duration-of-an-animated-gif
                    }
                    catch
                    {
                        timings[x] = 33;     // just set it to 30fps lul, works for consoles
                    }
                }
                return new Bitmap(i);
            }).
                           ToArray(), timings));
        }
Beispiel #3
0
    private List <Sprite> MyGif(System.Drawing.Image image)
    {
        List <Sprite> tex = new List <Sprite>();

        if (image != null)
        {
            Debug.Log("图片张数:" + image.FrameDimensionsList.Length);
            FrameDimension frame     = new FrameDimension(image.FrameDimensionsList[0]);
            int            framCount = image.GetFrameCount(frame); //获取维度帧数
            for (int i = 0; i < framCount; ++i)
            {
                image.SelectActiveFrame(frame, i);
                Bitmap framBitmap = new Bitmap(image.Width, image.Height);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(framBitmap))
                {
                    graphic.DrawImage(image, Point.Empty);
                }
                Texture2D frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);
                frameTexture2D.LoadImage(Bitmap2Byte(framBitmap));
                var sprite = Sprite.Create(frameTexture2D, new Rect(0, 0, frameTexture2D.width, frameTexture2D.height), new Vector2(0.5f, 0.5f));
                tex.Add(sprite);
            }
        }
        return(tex);
    }
Beispiel #4
0
        //-------------------------------------------------------------------------------
        //
        public ImageAnimation(Image img)
        {
            _image = img;
            FrameDimension = new FrameDimension(img.FrameDimensionsList[0]);
            MaxFrameCount = img.GetFrameCount(FrameDimension);
            PropertyItem pItemFrameDelay = img.GetPropertyItem(FRAME_DELAY);
            PropertyItem pItemFrameNum = img.GetPropertyItem(FRAME_NUM);
            FrameDelays = new int[MaxFrameCount];

            for (int i = 0; i < MaxFrameCount; i++) {
                FrameDelays[i] = BitConverter.ToInt32(pItemFrameDelay.Value, 4 * i);
            }
            MaxLoopCount = BitConverter.ToInt16(pItemFrameNum.Value, 0);

            LoopInfinity = (MaxLoopCount == 0);

            _timer = new Timer(Timer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
            try {
                _image.SelectActiveFrame(FrameDimension, 0);
            }
            catch (InvalidOperationException/* ex*/) {
                //Log.DebugLog(ex);
                //Debug.Assert(false, "Image.SelectActiveFrame失敗");
            }
        }
 public PagingImage(string filename)
 {
     _filename = filename;
     img = Bitmap.FromFile(filename);
     _pages = img.GetFrameCount(FrameDimension.Page);
     img.Dispose();
 }
Beispiel #6
0
        /// <summary>
        /// Return frame(s) as list of binary from jpeg, png, bmp or gif image file
        /// </summary>
        /// <param name="fileName">image file name</param>
        /// <returns>System.Collections.Generic.List of byte</returns>
        public static List <Bitmap> GetFrames(string fileName)
        {
            var tmpFrames = new List <byte[]>();

            // Check the image format to determine what format
            // the image will be saved to the memory stream in
            var guidToImageFormatMap = new Dictionary <Guid, ImageFormat>()
            {
                { ImageFormat.Bmp.Guid, ImageFormat.Bmp },
                { ImageFormat.Gif.Guid, ImageFormat.Png },
                { ImageFormat.Icon.Guid, ImageFormat.Png },
                { ImageFormat.Jpeg.Guid, ImageFormat.Jpeg },
                { ImageFormat.Png.Guid, ImageFormat.Png }
            };

            using (Image gifImg = Image.FromFile(fileName, true))
            {
                Guid imageGuid = gifImg.RawFormat.Guid;

                ImageFormat imageFormat = (from pair in guidToImageFormatMap where imageGuid == pair.Key select pair.Value).FirstOrDefault();

                if (imageFormat == null)
                {
                    throw new NoNullAllowedException("Unable to determine image format");
                }

                //Get the frame count
                var dimension  = new FrameDimension(gifImg.FrameDimensionsList[0]);
                int frameCount = gifImg.GetFrameCount(dimension);

                //Step through each frame
                for (int i = 0; i < frameCount; i++)
                {
                    //Set the active frame of the image and then
                    gifImg.SelectActiveFrame(dimension, i);

                    //write the bytes to the tmpFrames array
                    using (var ms = new MemoryStream())
                    {
                        gifImg.Save(ms, imageFormat);
                        tmpFrames.Add(ms.ToArray());
                    }
                }

                //Get list of frame(s) from image file.
                var myBitmaps = new List <Bitmap>();

                foreach (byte[] item in tmpFrames)
                {
                    Bitmap tmpBitmap = ConvertBytesToImage(item);

                    if (tmpBitmap != null)
                    {
                        myBitmaps.Add(tmpBitmap);
                    }
                }

                return(myBitmaps);
            }
        }
            /// <devdoc> 
            /// </devdoc>  
            public ImageInfo(Image image) {
                this.image = image;
                animated = ImageAnimator.CanAnimate(image);

                if (animated) {
                    frameCount = image.GetFrameCount(FrameDimension.Time);

                    PropertyItem frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay);

                    // If the image does not have a frame delay, we just return 0.                                     
                    //
                    if (frameDelayItem != null) {
                        // Convert the frame delay from byte[] to int
                        //
                        byte[] values = frameDelayItem.Value;
                        Debug.Assert(values.Length == 4 * FrameCount, "PropertyItem has invalid value byte array");
                        frameDelay = new int[FrameCount];
                        for (int i=0; i < FrameCount; ++i) {
                            frameDelay[i] = values[i * 4] + 256 * values[i * 4 + 1] + 256 * 256 * values[i * 4 + 2] + 256 * 256 * 256 * values[i * 4 + 3];
                        }
                    }
                }
                else {
                    frameCount = 1;
                }
                if (frameDelay == null) {
                    frameDelay = new int[FrameCount];
                }
            }                                               
    public void loadImage()
    {
        gifImage = ByteArrayToImage(www.bytes);

        if (gifImage == null)
        {
            return;
        }
        debugText.text = "Creating Image";
        var dimension  = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);

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

            //Debug.logger.Log("width: " + frame.Width + " height: " + frame.Height + " frame count: " + frameCount + " total: " + (frame.Width * frame.Height * frameCount));
            for (int x = 0; x < frame.Width; x++)
            {
                for (int y = 0; y < frame.Height; y++)
                {
                    System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                    frameTexture.SetPixel(frame.Width - 1 + x, -y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
                }
            }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
        }
        debugText.text = "Created Image";
        canOnGUI       = true;
    }
    /// <summary>
    /// Gif转Texture2D
    /// Crash fixed...
    /// </summary>
    /// <param name="image"> System.Image</param>
    /// <returns>Texture2D集合</returns>
    private void Gif2Texture2D(System.Drawing.Image image)
    {
        //List<Texture2D> tex = new List<Texture2D>();
        if (image != null)
        {
            // 图片构成有两种形式: 1、多页(.gif)  2、多分辨率..
            // 获取image对象的dimenson数,打印结果是1。..
            Debug.Log("image对象的dimenson数:" + image.FrameDimensionsList.Length);
            // image.FrameDimensionsList[0]-->获取image对象第一个dimension的 Guid(全局唯一标识符)....
            // 根据指定的GUID创建一个提供获取图像框架维度信息的实例..
            FrameDimension frameDimension = new FrameDimension(image.FrameDimensionsList[0]);
            // 获取指定维度的帧数
            int framCount = image.GetFrameCount(frameDimension);
            // 遍历图像帧
            for (int i = 0; i < framCount; i++)
            {
                // 选择由维度和索引指定的帧(激活图像帧);
                image.SelectActiveFrame(frameDimension, i);
                // 创建指定大小的 Bitmap 的实例。
                Bitmap framBitmap = new Bitmap(image.Width, image.Height);
                // Test:將Bitmap轉成PNG
                // framBitmap.Save("E:/Desktop/Saved_"+i+".png", System.Drawing.Imaging.ImageFormat.Png);

                // 从指定的Image 创建新的Graphics,并在指定的位置使用原始物理大小绘制指定的 Image,将当前激活帧的图形绘制到framBitmap上;
                // 简单点就是从 frameBitmap(里面什么都没画,是张白纸)创建一个Graphics,然后执行画画DrawImage
                // System.Drawing.Graphics.FromImage(framBitmap).DrawImage(image, Point.Empty);

                /*using (System.Drawing.Graphics newGraphics = System.Drawing.Graphics.FromImage(framBitmap))
                 * {
                 *      newGraphics.DrawImage(image, Point.Empty);
                 * }*/
                System.Drawing.Graphics.FromImage(framBitmap).DrawImage(image, Point.Empty);

                /*
                 * // 创建一个指定大小的 Texture2D 的实例
                 * Texture2D frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);
                 * // 执行Bitmap转Texture2D
                 * frameTexture2D.LoadImage(Bitmap2Byte(framBitmap));*/
                var frameTexture = new Texture2D(framBitmap.Width, framBitmap.Height);
                for (int x = 0; x < framBitmap.Width; x++)
                {
                    for (int y = 0; y < framBitmap.Height; y++)
                    {
                        System.Drawing.Color sourceColor = framBitmap.GetPixel(x, y);
                        frameTexture.SetPixel(framBitmap.Width - 1 - x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A));                           // for some reason, x is flipped
                    }
                }
                frameTexture.Apply();

                // 添加到列表中...
                tex2DList.Add(frameTexture);
                //Debug.Log (frameTexture);

                // Test:將Texture2D轉成PNG
                // var bytes = frameTexture2D.EncodeToPNG();
                // Destroy(frameTexture2D);
                // File.WriteAllBytes("E:/Desktop/Saved_" + i + ".png", bytes);
            }
        }
    }
Beispiel #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        public GifReader(Stream stream)
        {
            _gifImage = Image.FromStream(stream); //initialize

            _dimension = new FrameDimension(_gifImage.FrameDimensionsList[0]); //gets the GUID
            _frameCount = _gifImage.GetFrameCount(_dimension); //total frames in the animation
        }
        /// <summary>
        /// Getting the frames out of a GIF image.
        /// </summary>
        /// <param name="originalImg"></param>
        /// <returns></returns>
        public static BitmapImage[] GetFrames(Image originalImg)
        {
            int numberOfFrames = originalImg.GetFrameCount(FrameDimension.Time);

            Image[] frames = new System.Drawing.Image[numberOfFrames];

            BitmapImage[] bitmapFrames = new BitmapImage[numberOfFrames];

            for (int i = 0; i < numberOfFrames; i++)
            {
                originalImg.SelectActiveFrame(FrameDimension.Time, i);
                frames[i] = ((System.Drawing.Image)originalImg.Clone());
                using (var ms = new MemoryStream())
                {
                    frames[i].Save(ms, ImageFormat.Png);
                    ms.Seek(0, SeekOrigin.Begin);

                    var bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = ms;
                    bitmapImage.EndInit();

                    bitmapFrames[i] = bitmapImage;
                }
            }

            return(bitmapFrames);
        }
Beispiel #12
0
        public static string[] ConvertTiffToJpeg(string fileName)
        {
            using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName))
            {
                FrameDimension frameDimensions = new FrameDimension(
                    imageFile.FrameDimensionsList[0]);

                // Gets the number of pages from the tiff image (if multipage)
                int      frameNum  = imageFile.GetFrameCount(frameDimensions);
                string[] jpegPaths = new string[frameNum];

                for (int frame = 0; frame < frameNum; frame++)
                {
                    // Selects one frame at a time and save as jpeg.
                    imageFile.SelectActiveFrame(frameDimensions, frame);
                    using (Bitmap bmp = new Bitmap(imageFile))
                    {
                        jpegPaths[frame] = String.Format("{0}\\{1}{2}.jpg",
                                                         System.IO.Path.GetDirectoryName(fileName),
                                                         System.IO.Path.GetFileNameWithoutExtension(fileName),
                                                         (frameNum == 1 ? string.Empty : frame.ToString()));

                        bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
                    }
                }

                return(jpegPaths);
            }
        }
Beispiel #13
0
        public static void Iniciar()
        {
            Image          image      = Image.FromFile(@"C:\Users\900103\Desktop\terra1.gif");
            FrameDimension dimension  = new FrameDimension(image.FrameDimensionsList[0]);
            int            frameCount = image.GetFrameCount(dimension);
            StringBuilder  sb;

            int left = Console.WindowLeft, top = Console.WindowTop;

            char[] chars = { '.', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ' };

            for (int i = 0; ; i = (i + 1) % frameCount)
            {
                sb = new StringBuilder();
                image.SelectActiveFrame(dimension, i);

                for (int h = 0; h < image.Height; h++)
                {
                    for (int w = 0; w < image.Width; w++)
                    {
                        Color cl    = ((Bitmap)image).GetPixel(w, h);
                        int   gray  = (cl.R + cl.R + cl.B) / 3;
                        int   index = (gray * (chars.Length - 1)) / 255;

                        sb.Append(chars[index]);
                    }
                    sb.Append('\n');
                }

                Console.SetCursorPosition(left, top);
                Console.Write(sb.ToString());

                System.Threading.Thread.Sleep(200);
            }
        }
 public AnimatedImage(Image Image)
 {
     gifImage = Image; //initialize
     dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); //gets the GUID
     frameCount = gifImage.GetFrameCount(dimension); //total frames in the animation
     _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
 }
Beispiel #15
0
        /// <summary>
        /// 检查图片是不是动图或者长图或者二维码
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool CheckImage(string url, int minHeight, int minWidth)
        {
            int    FramesCount = 0;
            Stream fm          = null;

            try
            {
                //创建一个request 同时可以配置requst其余属性
                System.Net.WebRequest imgRequst = System.Net.WebRequest.Create(url);
                fm = imgRequst.GetResponse().GetResponseStream();
                //在这里我是以流的方式保存图片
                System.Drawing.Image downImage = System.Drawing.Image.FromStream(fm);
                FrameDimension       fd        = new FrameDimension(downImage.FrameDimensionsList[0]);
                FramesCount = downImage.GetFrameCount(fd);
                //图片大小
                if (downImage.Height <= minHeight || downImage.Width <= minWidth)
                {
                    return(true);
                }
                //是动图
                if (FramesCount > 1)
                {
                    return(true);
                }
                //使用ZXing识别二维码
                BarcodeReader reader = new BarcodeReader();
                reader.Options.CharacterSet = "UTF-8";
                var    map           = new Bitmap(downImage);
                Result resultStr     = reader.Decode(map);
                var    decodedString = resultStr == null ? "" : resultStr.Text;

                if (!string.IsNullOrEmpty(decodedString))
                {
                    return(true);
                }
                else
                {
                    //效率太低暂不使用
                    ////使用QRCode.Codec识别二维码
                    //QRCodeDecoder decoder = new QRCodeDecoder();
                    //decodedString = decoder.decode(new QRCodeBitmapImage(map),System.Text.Encoding.UTF8);
                    //if (!string.IsNullOrEmpty(decodedString))
                    //    return true;
                }
            }
            catch
            {
                if (fm != null)
                {
                    fm.Close();
                }
                return(false);
            }
            finally
            {
            }
            return(false);
        }
Beispiel #16
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        /// <param name="WatermarkText">水印文字</param>
        /// <param name="Watermarkimgpath">水印图片绝对地址</param>
        public bool addWaterMark(string oldpath, string newpath, DealType dealtype, WaterPos WatermarkPosition, string WatermarkText, string Watermarkimgpath)
        {
            bool re = false;

            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);

                foreach (Guid guid in image.FrameDimensionsList)//判断是否是GIF动画:是-则不加水印
                {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (image.GetFrameCount(dimension) > 1)
                    {
                        image.Dispose();
                        return(false);
                    }
                }

                Bitmap   b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode     = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                switch (dealtype)
                {
                //是图片的话
                case DealType.WM_IMAGE:
                    this.addWatermarkImage(g, Watermarkimgpath, WatermarkPosition, image.Width, image.Height);
                    break;

                //如果是文字
                case DealType.WM_TEXT:
                    this.addWatermarkText(g, WatermarkText, WatermarkPosition, image.Width, image.Height);
                    break;
                }

                //b.Save(newpath);
                //直接save加水印后图片容量大小会成几倍增加
                EncoderParameters parameters = new EncoderParameters(1);
                parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)80));
                b.Save(newpath, ImageHelper.GetCodecInfo("image/" + ImageHelper.GetFormat(newpath).ToString().ToLower()), parameters);

                b.Dispose();
                g.Dispose();
                image.Dispose();

                re = true;
            }
            catch
            {
                re = false;
            }
            return(re);
        }
Beispiel #17
0
 public GifImage(Image path)
 {
     gifImage = path;
     //initialize
     dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
     //gets the GUID
     //total frames in the animation
     frameCount = gifImage.GetFrameCount(dimension);
 }
Beispiel #18
0
		public GifHandler( Image Image ) {
			mImage = Image.Clone() as Image;
			mFrameDimension = new FrameDimension( mImage.FrameDimensionsList[ 0 ] );
			mFrameCount = mImage.GetFrameCount( mFrameDimension );

			mFrameTimes = new int[ mFrameCount ];
			byte[] times = mImage.GetPropertyItem( 0x5100 ).Value;
			for( int i = 0; i < mFrameCount; i++ )
				mFrameTimes[ i ] = BitConverter.ToInt32( times, 4 * i ) * 10;
		}
Beispiel #19
0
        private void GifBox(Image gif, PictureBox pic)
        {
            FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
            int count = gif.GetFrameCount(System.Drawing.Imaging.FrameDimension.Time);

            for (int i = 0; i < count; i++)
            {
                gif.SelectActiveFrame(fd, i);
                pic.Image = gif;
            }
        }
Beispiel #20
0
        public GifImage(string path)
        {
            _lastRequest = DateTime.Now;
            _gifImage = Image.FromFile(path); //initialize
            _dimension = new FrameDimension(_gifImage.FrameDimensionsList[0]); //gets the GUID
            FrameCount = _gifImage.GetFrameCount(_dimension); //total frames in the animation

            Source = path;

            var item = _gifImage.GetPropertyItem(0x5100); // FrameDelay in libgdiplus
            _delay = (item.Value[0] + item.Value[1]*256)*10; // Time is in 1/100th of a second
        }
Beispiel #21
0
        /// <summary>   
        /// 实例化一个AnimateImage。   
        /// </summary>   
        /// <param name="img">动画图片。</param>   
        public AnimateImage(Image img) {
            image = img;

            lock (image) {
                mCanAnimate = ImageAnimator.CanAnimate(image);
                if (mCanAnimate) {
                    Guid[] guid = image.FrameDimensionsList;
                    frameDimension = new FrameDimension(guid[0]);
                    mFrameCount = image.GetFrameCount(frameDimension);
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// 获取图片中的各帧
        /// </summary>
        /// <param name="pPath">图片路径</param>
        /// <param name="pSavedPath">保存路径</param>
        public static void GetFrames(string pPath, string pSavedPath)
        {
            System.Drawing.Image gif = System.Drawing.Image.FromFile(pPath);
            FrameDimension       fd  = new FrameDimension(gif.FrameDimensionsList[0]);
            int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)

            for (int i = 0; i < count; i++)    //以Jpeg格式保存各帧
            {
                gif.SelectActiveFrame(fd, i);
                gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GifDecoder"/> class.
        /// </summary>
        /// <param name="image">
        /// The <see cref="Image"/> to decode.
        /// </param>
        public GifDecoder(Image image)
        {
            this.Height = image.Height;
            this.Width = image.Width;

            if (FormatUtilities.IsAnimated(image))
            {
                this.IsAnimated = true;

                if (this.IsAnimated)
                {
                    int frameCount = image.GetFrameCount(FrameDimension.Time);
                    int last = frameCount - 1;
                    double length = 0;

                    List<GifFrame> gifFrames = new List<GifFrame>();

                    // Get the times stored in the gif.
                    byte[] times = image.GetPropertyItem((int)ExifPropertyTag.FrameDelay).Value;

                    for (int i = 0; i < frameCount; i++)
                    {
                        // Convert each 4-byte chunk into an integer.
                        // GDI returns a single array with all delays, while Mono returns a different array for each frame.
                        TimeSpan delay = TimeSpan.FromMilliseconds(BitConverter.ToInt32(times, (4 * i) % times.Length) * 10);

                        // Find the frame
                        image.SelectActiveFrame(FrameDimension.Time, i);
                        Bitmap frame = new Bitmap(image);
                        frame.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                        
                        // TODO: Get positions.
                        gifFrames.Add(new GifFrame { Delay = delay, Image = frame });

                        // Reset the position.
                        if (i == last)
                        {
                            image.SelectActiveFrame(FrameDimension.Time, 0);
                        }

                        length += delay.TotalMilliseconds;
                    }

                    this.GifFrames = gifFrames;
                    this.AnimationLength = length;

                    // Loop info is stored at byte 20737.
                    this.LoopCount = BitConverter.ToInt16(image.GetPropertyItem((int)ExifPropertyTag.LoopCount).Value, 0);
                    this.IsLooped = this.LoopCount != 1;
                }
            }
        }
Beispiel #24
0
 public static bool IsGIFAnimation(Image image)
 {
     System.Guid[] frameDimensionsList = image.FrameDimensionsList;
     for (int i = 0; i < frameDimensionsList.Length; i++)
     {
         System.Guid guid = frameDimensionsList[i];
         FrameDimension dimension = new FrameDimension(guid);
         if (image.GetFrameCount(dimension) > 1)
         {
             return true;
         }
     }
     return false;
 }
Beispiel #25
0
        public static Bitmap GetStackImage(Image image, int count, Item item) {
            if (image == null) return new Bitmap(item.image);
            int max = image.GetFrameCount(FrameDimension.Time);
            int index = 0;

            if (count <= 5) index = count - 1;
            else if (count <= 10) index = 5;
            else if (count <= 25) index = 6;
            else if (count <= 50) index = 7;
            else index = 8;

            if (index >= max) index = max - 1;
            image.SelectActiveFrame(FrameDimension.Time, index);
            return new Bitmap((Image)image.Clone());
        }
Beispiel #26
0
    /*/// <summary>
     * /// This method converts the read in byte arry to a System.Drawing.Bitmap
     * /// </summary>
     * /// <param name="data"> the byte array to be convereted</param>
     * /// <returns></returns>
     * public System.Drawing.Bitmap byteArrayToBitMap(byte[] data){
     * System.Drawing.Bitmap bmp;
     *
     * System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
     * bmp = (System.Drawing.Bitmap)ic.ConvertFrom(data);
     * //Debug.Log("Converted byteArray to bit map");
     * return bmp;
     *
     * }*/

    /*
     * public void byteArrayToTexture2D(byte[] data)
     * {
     *  int width = data[6];
     *  int height = data[8];
     *  Debug.Log("Width: " + width + " Height: " + height);
     *  Texture2D bmp = new Texture2D(width, height);
     *  bmp.LoadRawTextureData(data);
     *  myRawImage.texture = bmp;
     * }*/

    /// <summary>
    /// This handles loading all fo the data from the given url and converts it into a readable image type and then allows the OnGUI function to draw the gif
    /// </summary>
    public void loadImage()
    {
        //Debug.Log("Called Load Image BACK");
        gifImage = ByteArrayToImage(www.bytes);

        if (gifImage == null)
        {
            return;
        }

        isGif = true;

        var dimension  = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);

        Debug.Log("Dimensions: Frames: " + frameCount + " Width: " + gifImage.Width + " Height: " + gifImage.Height + " Pixels: " + (gifImage.Width * gifImage.Height));
        int width  = 0;
        int height = 0;



        for (int i = 0; i < frameCount; i++)
        {
            gifImage.SelectActiveFrame(dimension, i);
            var frame = new System.Drawing.Bitmap(gifImage.Width, gifImage.Height);

            System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);


            Texture2D frameTexture = new Texture2D(frame.Width, frame.Height);
            for (int x = 0; x < frame.Width; x++)
            {
                for (int y = 0; y < frame.Height; y++)
                {
                    System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                    frameTexture.SetPixel(frame.Width + x + 1, -y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
                }
            }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
            width  = frame.Width;
            height = frame.Height;
        }
        byteArrayTextConversion(bytearrayholder);
        //Debug.Log("Starting ON GUI!");
        canOnGUI = true;
    }
Beispiel #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GifDecoder"/> class.
        /// </summary>
        /// <param name="image">
        /// The <see cref="Image"/> to decode.
        /// </param>
        /// <param name="animationProcessMode">
        /// The <see cref="AnimationProcessMode" /> to use.
        /// </param>
        public GifDecoder(Image image, AnimationProcessMode animationProcessMode)
        {
            this.Height = image.Height;
            this.Width = image.Width;

            if (FormatUtilities.IsAnimated(image) && animationProcessMode == AnimationProcessMode.All)
            {
                this.IsAnimated = true;
                this.FrameCount = image.GetFrameCount(FrameDimension.Time);

                // Loop info is stored at byte 20737.
                this.LoopCount = BitConverter.ToInt16(image.GetPropertyItem((int)ExifPropertyTag.LoopCount).Value, 0);
            }
            else
            {
                this.FrameCount = 1;
            }
        }
Beispiel #28
0
        //-------------------------------------------------------------------------------
        //
        public ImageAnimation(Image img)
        {
            _image = img;
            FrameDimension = new FrameDimension(img.FrameDimensionsList[0]);
            MaxFrameCount = img.GetFrameCount(FrameDimension);
            PropertyItem pItemFrameDelay = img.GetPropertyItem(FRAME_DELAY);
            PropertyItem pItemFrameNum = img.GetPropertyItem(FRAME_NUM);
            FrameDelays = new int[MaxFrameCount];

            for (int i = 0; i < MaxFrameCount; i++) {
                FrameDelays[i] = BitConverter.ToInt32(pItemFrameDelay.Value, 4 * i);
            }
            MaxLoopCount = BitConverter.ToInt16(pItemFrameNum.Value, 0);

            LoopInfinity = (MaxLoopCount == 0);

            _timer = new Timer(Timer_Elapsed, null, Timeout.Infinite, Timeout.Infinite);
            _image.SelectActiveFrame(FrameDimension, 0);
        }
Beispiel #29
0
    public void LoadGif(string gifPath)
    {
        gifImage   = System.Drawing.Image.FromFile(gifPath);
        dimension  = new FrameDimension(gifImage.FrameDimensionsList[0]);
        frameCount = gifImage.GetFrameCount(dimension);

        gifFrames     = new Texture2D[frameCount];
        gifFramesLock = new bool[frameCount];

        for (int i = 0; i < frameCount; i++)
        {
            gifFramesLock[i] = false;
        }

        PropertyItem item = gifImage.GetPropertyItem(0x5100); // FrameDelay in libgdiplus

        delay = (item.Value[0] + item.Value[1] * 256) * 10;   // Time is in 1/100ths of a second

        StartCoroutine(LoadFramesLoop());
    }
Beispiel #30
0
        /// <summary>
        /// Gif转Texture2D
        /// </summary>
        /// <param name="image"> System.Image</param>
        /// <returns>Texture2D集合</returns>
        private List <Texture2D> Gif2Texture2D(System.Drawing.Image image)
        {
            var tex = new List <Texture2D>();

            if (image == null)
            {
                return(tex);
            }
            // 图片构成有两种形式: 1、多页(.gif)  2、多分辨率
            // 获取image对象的dimenson数,打印结果是1。
            Debug.Log("image对象的dimenson数:" + image.FrameDimensionsList.Length);
            // image.FrameDimensionsList[0]-->获取image对象第一个dimension的 Guid(全局唯一标识符)
            // 根据指定的GUID创建一个提供获取图像框架维度信息的实例
            var frameDimension = new FrameDimension(image.FrameDimensionsList[0]);

            // 获取指定维度的帧数
            _framCount = image.GetFrameCount(frameDimension);
            Debug.Log(_framCount);
            // 遍历图像帧
            for (var i = 0; i < _framCount; i++)
            {
                // 选择由维度和索引指定的帧(激活图像帧);
                image.SelectActiveFrame(frameDimension, i);
                // 创建指定大小的 Bitmap 的实例。
                var framBitmap = new Bitmap(image.Width, image.Height);
                // 从指定的Image 创建新的Graphics,并在指定的位置使用原始物理大小绘制指定的 Image,将当前激活帧的图形绘制到framBitmap上;
                // 简单点就是从 frameBitmap(里面什么都没画,是张白纸)创建一个Graphics,然后执行画画DrawImage
                using (var newGraphics = System.Drawing.Graphics.FromImage(framBitmap))
                {
                    newGraphics.DrawImage(image, Point.Empty);
                }
                // 创建一个指定大小的 Texture2D 的实例
                var frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);
                // 执行Bitmap转Texture2D
                frameTexture2D.LoadImage(Bitmap2Byte(framBitmap));
                // 添加到列表中
                tex.Add(frameTexture2D);
            }
            return(tex);
        }
Beispiel #31
0
        private void initAnimation()
        {
            var assembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var path     = System.IO.Path.GetDirectoryName(assembly);


            path = path + "\\Images\\progress_animation.gif";
            //log.Info("animation image path: " + path);
            animatedGifImage = System.Drawing.Image.FromFile(path);
            dimension        = new FrameDimension(animatedGifImage.FrameDimensionsList[0]);
            framesCount      = animatedGifImage.GetFrameCount(FrameDimension.Time);
            animationFrames  = new BitmapImage[framesCount];
            for (int frame = 0; frame < framesCount; ++frame)
            {
                animatedGifImage.SelectActiveFrame(dimension, frame);
                animationFrames[frame] = getBitmapImage(animatedGifImage);
            }

            currentFrame = 0;
            animatedGifImage.SelectActiveFrame(dimension, currentFrame);
            initTimer();
        }
Beispiel #32
0
        private static void ProcessingThread(byte[] gifData, AnimationInfo animationInfo)
        {
            System.Drawing.Image gifImage  = System.Drawing.Image.FromStream(new MemoryStream(gifData));
            FrameDimension       dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
            int frameCount = gifImage.GetFrameCount(dimension);

            animationInfo.frameCount  = frameCount;
            animationInfo.initialized = true;
            animationInfo.frames      = new List <FrameInfo>(frameCount);

            int firstDelayValue = -1;

            var delays = gifImage.GetPropertyItem(20736).Value;

            for (int i = 0; i < frameCount; i++)
            {
                gifImage.SelectActiveFrame(dimension, i);

                using (Bitmap bitmap = new Bitmap(gifImage)) {
                    bitmap.MakeTransparent(System.Drawing.Color.Black);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);

                    BitmapData frame        = bitmap.LockBits(new Rectangle(Point.Empty, gifImage.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    FrameInfo  currentFrame = new FrameInfo(frame.Width, frame.Height);

                    Marshal.Copy(frame.Scan0, currentFrame.colors, 0, currentFrame.colors.Length);

                    int delayPropertyValue = BitConverter.ToInt32(delays, i * 4);
                    if (firstDelayValue == -1)
                    {
                        firstDelayValue = delayPropertyValue;
                    }

                    currentFrame.delay = delayPropertyValue * 10;
                    animationInfo.frames.Add(currentFrame);
                }
            }
        }
        public static bool CanAnimate(Image image)
        {
            if (image == null)
            {
                return(false);
            }

            int n = image.FrameDimensionsList.Length;

            if (n < 1)
            {
                return(false);
            }

            for (int i = 0; i < n; i++)
            {
                if (image.FrameDimensionsList[i].Equals(FrameDimension.Time.Guid))
                {
                    return(image.GetFrameCount(FrameDimension.Time) > 1);
                }
            }
            return(false);
        }
        /// <summary>
        /// Convert an Image to a spritesheet
        /// </summary>
        /// <param name="gif">The original gif file</param>
        /// <param name="columns">How many columns to use</param>
        /// <returns></returns>
        public Bitmap GifToSpritesheet(System.Drawing.Image gif, int columns = 1)
        {
            FrameDimension frameSize = new FrameDimension(gif.FrameDimensionsList[0]);

            System.Drawing.Size imageSize = new System.Drawing.Size(gif.Size.Width, gif.Size.Height);
            int      frames = gif.GetFrameCount(frameSize);
            int      rows   = (int)Math.Ceiling((double)frames / columns);
            Bitmap   bitmap = new Bitmap(columns * imageSize.Width, rows * imageSize.Height);
            Graphics g      = Graphics.FromImage(bitmap);

            // In case of adding a background color
//            Brush brush = new SolidBrush(somecolor);
//            g.FillRectangle(brush, new Rectangle(0, 0, bitmap.Width, bitmap.Height));

            for (int i = 0; i < frames; i++)
            {
                gif.SelectActiveFrame(frameSize, i);
                g.DrawImage(gif, i % columns * imageSize.Width, i / columns * imageSize.Height);
            }
            g.Dispose();

            return(bitmap);
        }
Beispiel #35
0
        /// <devdoc>
        ///    Whether or not the image has multiple time-based frames.
        /// </devdoc>
        public static bool CanAnimate(Image image)
        {
            if (image == null)
            {
                return(false);
            }

            // See comment in the class header about locking the image ref.
            lock ( image ) {
                Guid[] dimensions = image.FrameDimensionsList;

                foreach (Guid guid in dimensions)
                {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (dimension.Equals(FrameDimension.Time))
                    {
                        return(image.GetFrameCount(FrameDimension.Time) > 1);
                    }
                }
            }

            return(false);
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            //Thank you Сергей Кровлин
            //His Youtube link is under my video.
            Image          image      = Image.FromFile(@"C:\Users\franc\OneDrive\Área de Trabalho\1KILE.gif");
            FrameDimension dimension  = new FrameDimension(image.FrameDimensionsList[0]);
            int            frameCount = image.GetFrameCount(dimension);
            StringBuilder  sb;

            int left = Console.WindowLeft, top = Console.WindowTop;

            char[] chars = { '#', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ' };

            for (int i = 0; ; i = (i + 1) % frameCount)
            {
                sb = new StringBuilder();
                image.SelectActiveFrame(dimension, i);

                for (int h = 0; h < image.Height; h++)
                {
                    for (int w = 0; w < image.Width; w++)
                    {
                        Color cl    = ((Bitmap)image).GetPixel(w, h);
                        int   gray  = (cl.R + cl.R + cl.B) / 3;
                        int   index = (gray * (chars.Length - 1)) / 255;

                        sb.Append(chars[index]);
                    }
                    sb.Append('\n');
                }

                Console.SetCursorPosition(left, top);
                Console.Write(sb.ToString());

                System.Threading.Thread.Sleep(600);
            }
        }
Beispiel #37
0
        public override bool LoadImageData(String pathToGifFile, ImageSequence destImageSequence)
        {
            if (File.Exists(pathToGifFile) && Path.GetExtension(pathToGifFile).ToUpper() == ".GIF")
            {
                System.Drawing.Image gifImg = System.Drawing.Image.FromFile(pathToGifFile);
                if (gifImg != null)
                {
                    FrameDimension dimension = new FrameDimension(gifImg.FrameDimensionsList[0]);
                    // Number of frames
                    int frameCount = gifImg.GetFrameCount(dimension);

                    for (int i = 0; i < frameCount; i++)
                    {
                        // Return an Image at a certain index
                        gifImg.SelectActiveFrame(dimension, i);
                        ImageBuffer frame = new ImageBuffer();
                        ConvertBitmapToImage(frame, new Bitmap(gifImg));
                        destImageSequence.AddImage(frame);
                    }

                    try
                    {
                        PropertyItem item = gifImg.GetPropertyItem(0x5100);                         // FrameDelay in libgdiplus
                        // Time is in 1/100th of a second
                        destImageSequence.SecondsPerFrame = (item.Value[0] + item.Value[1] * 256) / 100.0;
                    }
                    catch
                    {
                        destImageSequence.SecondsPerFrame = 2;
                    }

                    return(true);
                }
            }

            return(false);
        }
Beispiel #38
0
    /// <summary>
    /// gif to List<Texture2D>
    /// </summary>
    /// <param name="gifImage"></param>
    /// <returns></returns>
    List<Texture2D> GifToTexture2D(System.Drawing.Image gifImage)
    {
        List<Texture2D> target = null;
        if (gifImage != null)
        {
            target = new List<Texture2D>();

            //图片的构成有两种形式:1.多页(.gif) 2.多分辨率
            Debug.Log("dimenson:" + gifImage.FrameDimensionsList.Length);

            //根据指定的GUID(gifImage.FrameDimensionsList[0])
            //创建一个提供获取图像框架维度信息的实例
            FrameDimension frameDimension = new FrameDimension(gifImage.FrameDimensionsList[0]);

            int frameCount = gifImage.GetFrameCount(frameDimension);
            for (int i = 0; i < frameCount; i++)
            {
                gifImage.SelectActiveFrame(frameDimension, i);

                //创建Bitmap的实例
                Bitmap frameBitmap = new Bitmap(gifImage.Width, gifImage.Height);

                //将GifImage通过Graphics画到Bitmap上
                using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(frameBitmap))
                {
                    graphics.DrawImage(gifImage, Point.Empty);
                }

                //创建Texture2D的实例
                Texture2D frameTexture2D = new Texture2D(frameBitmap.Width, frameBitmap.Height, TextureFormat.ARGB32, true);
                frameTexture2D.LoadImage(Bitmap2Byte(frameBitmap));
                target.Add(frameTexture2D);
            }
        }
        Debug.Log("编译完成");
        return target;
    }
Beispiel #39
0
        public override bool LoadImageData(Stream stream, ImageSequence destImageSequence)
        {
            System.Drawing.Image gifImg = System.Drawing.Image.FromStream(stream);
            if (gifImg != null)
            {
                FrameDimension dimension = new FrameDimension(gifImg.FrameDimensionsList[0]);
                // Number of frames
                int frameCount = gifImg.GetFrameCount(dimension);

                for (int i = 0; i < frameCount; i++)
                {
                    // Return an Image at a certain index
                    gifImg.SelectActiveFrame(dimension, i);
                    ImageBuffer frame = new ImageBuffer();
                    ConvertBitmapToImage(frame, new Bitmap(gifImg));
                    destImageSequence.AddImage(frame);
                }

                try
                {
                    PropertyItem item = gifImg.GetPropertyItem(0x5100);                     // FrameDelay in libgdiplus
                    // Time is in 1/100th of a second
                    destImageSequence.SecondsPerFrame = (item.Value[0] + item.Value[1] * 256) / 100.0;
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    destImageSequence.SecondsPerFrame = 2;
                }

                return(true);
            }

            return(false);
        }
    private List <byte[]> GetBytesFromImage(System.Drawing.Image image)
    {
        List <byte[]> tex = new List <byte[]>();

        if (image != null)
        {
            FrameDimension frame = new FrameDimension(image.FrameDimensionsList[0]);
            //获取维度帧数
            int frameCount = image.GetFrameCount(frame);
            for (int i = 0; i < frameCount; ++i)
            {
                image.SelectActiveFrame(frame, i);
                using (MemoryStream stream = new MemoryStream())
                {
                    image.Save(stream, ImageFormat.Png);
                    byte[] data = new byte[stream.Length];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(data, 0, Convert.ToInt32(stream.Length));
                    tex.Add(data);
                }
            }
        }
        return(tex);
    }
Beispiel #41
0
            public ImageInfo(Image image)
            {
                _image      = image;
                _animated   = ImageAnimator.CanAnimate(image);
                _frameDelay = null !; // guaranteed to be initialized by the final check

                if (_animated)
                {
                    _frameCount = image.GetFrameCount(FrameDimension.Time);

                    PropertyItem?frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay);

                    // If the image does not have a frame delay, we just return 0.
                    //
                    if (frameDelayItem != null)
                    {
                        // Convert the frame delay from byte[] to int
                        //
                        byte[] values = frameDelayItem.Value !;
                        Debug.Assert(values.Length == 4 * FrameCount, "PropertyItem has invalid value byte array");
                        _frameDelay = new int[FrameCount];
                        for (int i = 0; i < FrameCount; ++i)
                        {
                            _frameDelay[i] = values[i * 4] + 256 * values[i * 4 + 1] + 256 * 256 * values[i * 4 + 2] + 256 * 256 * 256 * values[i * 4 + 3];
                        }
                    }
                }
                else
                {
                    _frameCount = 1;
                }
                if (_frameDelay == null)
                {
                    _frameDelay = new int[FrameCount];
                }
            }
Beispiel #42
0
        public void DisposeImg(Image img)
        {
            try
            {
                if (img != null)
                {
                    if (img.GetFrameCount(new FrameDimension(img.FrameDimensionsList[0])) > 1)
                        ImageAnimator.StopAnimate(img, new EventHandler(this.OnFrameChanged));

                    img.Dispose();
                }
            }
            catch
            {
                //img is disposed so do nothing
            }
        }
Beispiel #43
0
 public static int GetFrameCount(this Image image) => image.GetFrameCount(new FrameDimension(image.FrameDimensionsList.First()));
Beispiel #44
0
        /// <summary>
        /// Checks and restores an animated GIF.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <remarks>Documented by Dev03, 2008-03-21</remarks>
        private void CheckAndRestoreGIF(ref Image image)
        {
            if (!image.RawFormat.Guid.Equals(ImageFormat.Gif.Guid))
                return;

            List<int> badframeIndexes = new List<int>();
            int count = 0;

            count = image.GetFrameCount(FrameDimension.Time);

            if (count > 1)
            {
                //string fn = Path.GetTempFileName();
                //image.Save(fn);
                //image = Image.FromFile(fn);

                //MemoryStream str = new MemoryStream();
                //image.Save(str, ImageFormat.Gif);
                //str.Seek(0, SeekOrigin.Begin);
                //image = Image.FromStream(str);
            }

            for (int i = 0; i < count; i++)
            {
                try
                {
                    image.SelectActiveFrame(FrameDimension.Time, i);
                }
                catch
                {
                    badframeIndexes.Add(i);
                }
            }
            if (badframeIndexes.Count > 0)
            {
                string indexes = String.Empty;
                for (int i = 0; i < badframeIndexes.Count; i++)
                {
                    indexes += badframeIndexes[i].ToString() + ",";
                }
                indexes = indexes.Substring(0, indexes.Length - 1);
                System.Diagnostics.Debug.Write("Frames No." + indexes + " are damaged!");
            }
            else
            {
                return;
            }

            if ((badframeIndexes.Count) > 0 && (badframeIndexes.Count < count))
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    EncoderParameters encoderpara = new EncoderParameters(1);

                    for (int i = 0; i < count; i++)
                    {
                        if (!badframeIndexes.Contains(i))
                        {
                            image.SelectActiveFrame(FrameDimension.Time, i);
                            image.Save(stream, ImageFormat.Png);
                            break;
                        }
                    }
                    image = Bitmap.FromStream(stream);
                }
            }
        }
Beispiel #45
0
        internal static void EnsureSave(Image image, string filename, Stream dataStream) {

            if (image.RawFormat.Equals(ImageFormat.Gif)) {
                bool animatedGif = false;

                Guid[] dimensions = image.FrameDimensionsList;
                foreach (Guid guid in dimensions) {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (dimension.Equals(FrameDimension.Time)) {
                        animatedGif = image.GetFrameCount(FrameDimension.Time) > 1;
                        break;
                    }
                }


                if (animatedGif) {
                    try {
                        Stream created = null;
                        long lastPos = 0;
                        if (dataStream != null) {
                            lastPos = dataStream.Position;
                            dataStream.Position = 0;
                        }

                        try {
                            if (dataStream == null) {
                                created = dataStream = File.OpenRead(filename);
                            }

                            image.rawData = new byte[(int)dataStream.Length];
                            dataStream.Read(image.rawData, 0, (int)dataStream.Length);
                        }
                        finally {
                            if (created != null) {
                                created.Close();
                            }
                            else {
                                dataStream.Position = lastPos;
                            }
                        }
                    }
                    // possible exceptions for reading the filename
                    catch (UnauthorizedAccessException) {
                    }
                    catch (DirectoryNotFoundException) {
                    }
                    catch (IOException) {
                    }
                    // possible exceptions for setting/getting the position inside dataStream
                    catch (NotSupportedException) {
                    }
                    catch (ObjectDisposedException) {
                    }
                    // possible exception when reading stuff into dataStream
                    catch (ArgumentException) {
                    }
                }
            }
        }
    public static int LoadFromMemory(Image memoryImage, string name, long lColorKey, int iMaxWidth, int iMaxHeight)
    {
      Log.Debug("TextureManager: load from memory: {0}", name);
      string cacheName = name;
      string cacheKey = name.ToLowerInvariant();

      CachedTexture cached;
      if (_cacheTextures.TryGetValue(cacheKey, out cached))
      {
        return cached.Frames;
      }

      if (memoryImage == null)
      {
        return 0;
      }
      if (memoryImage.FrameDimensionsList == null)
      {
        return 0;
      }
      if (memoryImage.FrameDimensionsList.Length == 0)
      {
        return 0;
      }

      try
      {
        CachedTexture newCache = new CachedTexture();

        newCache.Name = cacheName;
        FrameDimension oDimension = new FrameDimension(memoryImage.FrameDimensionsList[0]);
        newCache.Frames = memoryImage.GetFrameCount(oDimension);
        if (newCache.Frames != 1)
        {
          return 0;
        }
        //load gif into texture
        using (MemoryStream stream = new MemoryStream())
        {
          memoryImage.Save(stream, ImageFormat.Png);
          ImageInformation info2 = new ImageInformation();
          stream.Flush();
          stream.Seek(0, SeekOrigin.Begin);
          Texture texture = TextureLoader.FromStream(
            GUIGraphicsContext.DX9Device,
            stream,
            0, 0, //width/height
            1, //mipslevels
            0, //Usage.Dynamic,
            Format.A8R8G8B8,
            GUIGraphicsContext.GetTexturePoolType(),
            Filter.None,
            Filter.None,
            (int)lColorKey,
            ref info2);
          newCache.Width = info2.Width;
          newCache.Height = info2.Height;
          newCache.Texture = new TextureFrame(cacheName, texture, 0);
        }
        memoryImage.SafeDispose();
        memoryImage = null;
        newCache.Disposed += new EventHandler(cachedTexture_Disposed);

        _cacheTextures[cacheKey] = newCache;

        Log.Debug("TextureManager: added: memoryImage  " + " total count: " + _cacheTextures.Count + ", mem left (MB): " +
                  ((uint)GUIGraphicsContext.DX9Device.AvailableTextureMemory / 1048576));
        return newCache.Frames;
      }
      catch (Exception ex)
      {
        Log.Error("TextureManager: exception loading texture memoryImage");
        Log.Error(ex);
      }
      return 0;
    }
Beispiel #47
0
 public static Image selectLargestPage( Image img )
 {
     if ( img==null )
         return null;
     int nLargestIndex = 0;
     int nLargestSize = 0;
     int nCount = img.GetFrameCount( FrameDimension.Page );
     if ( nCount==1 )
         return img;
     for ( var i=0 ; i<nCount ; i++ )
     {
         img.SelectActiveFrame( FrameDimension.Page, i );
         if ( img.Size.Width > nLargestSize )
         {
             nLargestSize = img.Size.Width;
             nLargestIndex = i;
         }
     }
     img.SelectActiveFrame( FrameDimension.Page, nLargestIndex );
     return img;
 }
Beispiel #48
0
        private void btnOpenImage_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "All Supported Images(*.BMP,*.PNG,*.JPEG,*.JPG,*.JPE,*.JFIF,*.TIF,*.TIFF,*.GIF)|*.BMP;*.PNG;*.JPEG;*.JPG;*.JPE;*.JFIF;*.TIF;*.TIFF;*.GIF|JPEG|*.JPG;*.JPEG;*.JPE;*.JFIF|BMP|*.BMP|PNG|*.PNG|TIFF|*.TIF;*.TIFF|GIF|*.GIF";
                dlg.InitialDirectory = lastOpenedDirectory;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    lastOpenedDirectory = System.IO.Directory.GetParent(dlg.FileName).FullName;
                    if (m_data != null)
                    {
                        m_data.Dispose();
                        m_data = null;
                        iPageCount = 0;
                    }
                    m_results.Clear();
                    tbResults.Clear();

                    this.Text = dlg.FileName;

                    filePath = dlg.FileName;

                    m_data = Image.FromFile(filePath);
                    if (m_data.RawFormat.Equals(ImageFormat.Gif))
                        iPageCount = 1;
                    else
                    {
                        iPageCount = m_data.GetFrameCount(new FrameDimension(m_data.FrameDimensionsList[0]));
                    }

                    if (iPageCount > 0 && iCheckedFormatCount > 0)
                        btnRead.Enabled = true;
                    CurrentIndex = iPageCount - 1;
                    tbxTotalImageNum.Text = iPageCount.ToString();
                    if (iPageCount > 1)
                    {
                        EnableControls(picboxFirst);
                        EnableControls(picboxPrevious);
                        //EnableControls(picboxNext);
                        //EnableControls(picboxLast);
                    }
                    else
                    {
                        DisableControls(picboxFirst);
                        DisableControls(picboxPrevious);
                        DisableControls(picboxNext);
                        DisableControls(picboxLast);
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Barcode Reader Demo", MessageBoxButtons.OK);
            }
        }
Beispiel #49
0
 Image[] getFrames(Image originalImg)
 {
     int numberOfFrames = originalImg.GetFrameCount(FrameDimension.Time);
     Image[] frames = new Image[numberOfFrames];
     for (int i = 0; i < numberOfFrames; i++)
     {
         originalImg.SelectActiveFrame(FrameDimension.Time, i);
         frames[i] = ((Image)originalImg.Clone());
     }
     return frames;
 }
Beispiel #50
0
 private Image[] TrySplitImage(Image master)
 {
     var dimension = new FrameDimension(master.FrameDimensionsList[0]);
     var images = new Image[master.GetFrameCount(dimension)];
     for (var i = 0; i < images.Length; i++) {
         master.SelectActiveFrame(dimension, i);
         images[i] = new Bitmap(master);
     }
     return images;
 }
Beispiel #51
0
        private void loadImage(Guid guid)
        {
            try
            {
                this.Show();
                if (_strFilePath == null)
                {
                    ultraToolbarsManagerStandard.Tools["PdfConvert"].SharedProps.Enabled = false;
                    ultraToolbarsManagerStandard.Tools["Delete"].SharedProps.Enabled = false;
                    ultraToolbarsManagerStandard.Tools["ZoomIn"].SharedProps.Enabled = false;
                    ultraToolbarsManagerStandard.Tools["ZoomOut"].SharedProps.Enabled = false;
                    ultraToolbarsManagerStandard.Tools["RotateLeft"].SharedProps.Enabled = false;
                    ultraToolbarsManagerStandard.Tools["RotateRight"].SharedProps.Enabled = false;
                    if (_ultraToolbarAttivita != null)
                    {
                        _ultraToolbarAttivita.Visible = false;
                        _ultraMenuAttivita.SharedProps.Visible = false;
                    }
                }
                else
                {
                    ultraToolbarsManagerStandard.Tools["PdfConvert"].SharedProps.Enabled = true;
                    ultraToolbarsManagerStandard.Tools["Delete"].SharedProps.Enabled = true;
                    ultraToolbarsManagerStandard.Tools["ZoomIn"].SharedProps.Enabled = true;
                    ultraToolbarsManagerStandard.Tools["ZoomOut"].SharedProps.Enabled = true;
                    ultraToolbarsManagerStandard.Tools["RotateLeft"].SharedProps.Enabled = true;
                    ultraToolbarsManagerStandard.Tools["RotateRight"].SharedProps.Enabled = true;
                    if (_ultraToolbarAttivita != null)
                    {
                        _ultraToolbarAttivita.Visible = true;
                        _ultraMenuAttivita.SharedProps.Visible = true;
                    }

                    _imageGuid = guid;
                    picBoxSize();

                    // Changed the cursor to waitCursor
                    Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    // Sets the tiff file as an image object.
                    _objImage = System.Drawing.Image.FromFile(_strFilePath);
                    Guid objGuid = _objImage.FrameDimensionsList[0];
                    System.Drawing.Imaging.FrameDimension objDimension = new System.Drawing.Imaging.FrameDimension(objGuid);

                    //Gets the total number of frames in the .tiff file
                    _totFrame = _objImage.GetFrameCount(objDimension);
                    if (_totFrame > 1)
                        base.ultraToolbarsManagerStandard.Tools["Next"].SharedProps.Enabled = true;

                    //Adds number of frames to the combo box for displaying purposes.
                    _cboFrameNo.ResetValueList();
                    for (int i = 1; i <= _totFrame; i++)
                    {
                        _cboFrameNo.ValueList.ValueListItems.Add(new Infragistics.Win.ValueListItem(i, i.ToString()));
                    }

                    //Sets the temporary folder
                    _strPath = System.IO.Path.GetTempPath() + "FaxGest\\";

                    //Saves every frame as a seperate file.
                    _curF = 0;
                    for (int z = 0; z < _totFrame; z++)
                    {
                        _objImage.SelectActiveFrame(objDimension, _curF);
                        _objImage.Save(_strPath + _imageGuid + "_" + _curF + ".tif", System.Drawing.Imaging.ImageFormat.Tiff);
                        _curF++;
                    }
                    _curF = 0;

                    // Displayes the frames
                    displayFrame();
                    Cursor = System.Windows.Forms.Cursors.Default;
                }
            }

            catch { }

        }
Beispiel #52
0
		public static bool CanAnimate (Image image)
		{
			if (image == null)
				return false;

			int n = image.FrameDimensionsList.Length;
			if (n < 1)
				return false;

			for (int i = 0; i < n; i++) {
				if (image.FrameDimensionsList [i].Equals (FrameDimension.Time.Guid)) {
					return (image.GetFrameCount (FrameDimension.Time) > 1);
				}
			}
			return false;
		}
Beispiel #53
0
		public AnimateEventArgs (Image image)
		{
			frameCount = image.GetFrameCount (FrameDimension.Time);
		}
 public AnimateEventArgs(Image image)
 {
     frameCount = image.GetFrameCount(FrameDimension.Time);
 }
Beispiel #55
0
 private void InitImage(Image image)
 {
     _gifImage = image;
     _dimension = new FrameDimension(_gifImage.FrameDimensionsList[0]);
     _frameCount = _gifImage.GetFrameCount(_dimension);
 }
Beispiel #56
0
 public static bool IsGif(Image img)
 {
     Guid[] guids = img.FrameDimensionsList;
     FrameDimension fd = new FrameDimension(guids[0]);
     return img.GetFrameCount(fd) > 1;
 }
Beispiel #57
0
            public ImageInfo(Image image)
            {
                _image         = image;
                _animated      = ImageAnimator.CanAnimate(image);
                _frameEndTimes = null;

                if (_animated)
                {
                    _frameCount = image.GetFrameCount(FrameDimension.Time);

                    PropertyItem?frameDelayItem = image.GetPropertyItem(PropertyTagFrameDelay);

                    // If the image does not have a frame delay, we just return 0.
                    if (frameDelayItem != null)
                    {
                        // Convert the frame delay from byte[] to int
                        byte[] values = frameDelayItem.Value !;

                        // On Windows, we get the frame delays for every frame. On Linux, we only get the first frame delay.
                        // We handle this by treating the frame delays as a repeating sequence, asserting that the sequence
                        // is fully repeatable to match the frame count.
                        Debug.Assert(values.Length % 4 == 0, "PropertyItem has an invalid value byte array. It should have a length evenly divisible by 4 to represent ints.");
                        Debug.Assert(_frameCount % (values.Length / 4) == 0, "PropertyItem has invalid value byte array. The FrameCount should be evenly divisible by a quarter of the byte array's length.");

                        _frameEndTimes = new long[_frameCount];
                        long lastEndTime = 0;

                        for (int f = 0, i = 0; f < _frameCount; ++f, i += 4)
                        {
                            if (i >= values.Length)
                            {
                                i = 0;
                            }

                            // Frame delays are stored in 1/100ths of a second; convert to milliseconds while accumulating
                            // Per spec, a frame delay can be 0 which is treated as a single animation tick
                            int delay = BitConverter.ToInt32(values, i) * 10;
                            lastEndTime += delay > 0 ? delay : ImageAnimator.AnimationDelayMS;

                            // Guard against overflows
                            if (lastEndTime < _totalAnimationTime)
                            {
                                lastEndTime = _totalAnimationTime;
                            }
                            else
                            {
                                _totalAnimationTime = lastEndTime;
                            }

                            _frameEndTimes[f] = lastEndTime;
                        }
                    }

                    PropertyItem?loopCountItem = image.GetPropertyItem(PropertyTagLoopCount);

                    if (loopCountItem != null)
                    {
                        // The loop count is a short where 0 = infinite, and a positive value indicates the
                        // number of times to loop. The animation will be shown 1 time more than the loop count.
                        byte[] values = loopCountItem.Value !;

                        Debug.Assert(values.Length == sizeof(short), "PropertyItem has an invalid byte array. It should represent a single short value.");
                        _loopCount = BitConverter.ToInt16(values);
                    }
                    else
                    {
                        _loopCount = 0;
                    }
                }
                else
                {
                    _frameCount = 1;
                }
            }
        /// <devdoc>
        ///    Whether or not the image has multiple time-based frames.
        /// </devdoc>
        public static bool CanAnimate(Image image) {
            if( image == null ) {
                return false;
            }

            // See comment in the class header about locking the image ref.
            lock( image ) {
                Guid[] dimensions = image.FrameDimensionsList;
                    
                foreach (Guid guid in dimensions) {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (dimension.Equals(FrameDimension.Time)) {
                        return image.GetFrameCount(FrameDimension.Time) > 1;
                    }
                }
            }

            return false;
        }
Beispiel #59
0
        internal static void EnsureSave(Image image, string filename, Stream dataStream)
        {
            if (image.RawFormat.Equals(ImageFormat.Gif))
            {
                bool animatedGif = false;

                Guid[] dimensions = image.FrameDimensionsList;
                foreach (Guid guid in dimensions)
                {
                    FrameDimension dimension = new FrameDimension(guid);
                    if (dimension.Equals(FrameDimension.Time))
                    {
                        animatedGif = image.GetFrameCount(FrameDimension.Time) > 1;
                        break;
                    }
                }


                if (animatedGif)
                {
                    try
                    {
                        Stream created = null;
                        long   lastPos = 0;
                        if (dataStream != null)
                        {
                            lastPos             = dataStream.Position;
                            dataStream.Position = 0;
                        }

                        try
                        {
                            if (dataStream == null)
                            {
                                created = dataStream = File.OpenRead(filename);
                            }

                            image._rawData = new byte[(int)dataStream.Length];
                            dataStream.Read(image._rawData, 0, (int)dataStream.Length);
                        }
                        finally
                        {
                            if (created != null)
                            {
                                created.Close();
                            }
                            else
                            {
                                dataStream.Position = lastPos;
                            }
                        }
                    }
                    // possible exceptions for reading the filename
                    catch (UnauthorizedAccessException)
                    {
                    }
                    catch (DirectoryNotFoundException)
                    {
                    }
                    catch (IOException)
                    {
                    }
                    // possible exceptions for setting/getting the position inside dataStream
                    catch (NotSupportedException)
                    {
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                    // possible exception when reading stuff into dataStream
                    catch (ArgumentException)
                    {
                    }
                }
            }
        }
    public void loadImage()
    {
        gifImage = ByteArrayToImage(www.bytes);

        if (gifImage == null)
            return;
        debugText.text = "Creating Image";
        var dimension = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);
        for (int i = 0; i < frameCount; i++)
        {
            gifImage.SelectActiveFrame(dimension, i);
            var frame = new System.Drawing.Bitmap(gifImage.Width, gifImage.Height);
            System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, System.Drawing.Point.Empty);
            Texture2D frameTexture = new Texture2D(frame.Width, frame.Height);

            //Debug.logger.Log("width: " + frame.Width + " height: " + frame.Height + " frame count: " + frameCount + " total: " + (frame.Width * frame.Height * frameCount));
            for (int x = 0; x < frame.Width; x++)
                for (int y = 0; y < frame.Height; y++)
                {
                    System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                    frameTexture.SetPixel(frame.Width - 1 + x, -y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
                }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
        }
        debugText.text = "Created Image";
        canOnGUI = true;
    }