C#中 读取图片后不锁定图片的方法
//170216.JJ method that will lock image file: //picConn.Image = Image.FromFile(strPath); //170216.JJ method that will unlock after read. Image img; using (var bmpTemp = new Bitmap(strPath)) { img = new Bitmap(bmpTemp); } picConn.Image = img;
----------------------
2018.06.01 今天又有了新的需求,需要加载GIF动画,所以之前的new Bitmap就不行了。
可以通过stream的形式读取.
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { gifImage = Image.FromStream(stream); }
但是读取完就不能实时换帧,调用gifImage.SelectActiveFrame(dimension, i)的时候会报错。
只好一次性把所有的帧都读回来,存起来。
代码如下:亲测可用
public class GifImage { private Image gifImage; private FrameDimension dimension; private Image[] imgList; private int frameCount; private int currentFrame = -1; private bool reverse; private int step = 1; public GifImage(string path) { //gifImage = Image.FromFile(path);// This method would lock the file using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { gifImage = Image.FromStream(stream); //initialize dimension = new FrameDimension(gifImage.FrameDimensionsList[0]); //gets the GUID //total frames in the animation frameCount = gifImage.GetFrameCount(dimension); //Store each frame imgList = new Image[frameCount]; for (int i = 0; i < frameCount; i++) { gifImage.SelectActiveFrame(dimension, i);//This action requires the stream opened. imgList[i] = (Image)gifImage.Clone(); } } } public bool ReverseAtEnd { //whether the gif should play backwards when it reaches the end get { return reverse; } set { reverse = value; } } public Image GetNextFrame() { currentFrame += step; //if the animation reaches a boundary... if (currentFrame >= frameCount || currentFrame < 1) { if (reverse) { step *= -1; //...reverse the count //apply it currentFrame += step; } else { currentFrame = 0; //...or start over } } return GetFrame(currentFrame); } public Image GetFrame(int index) { return imgList[index]; // gifImage.SelectActiveFrame(dimension, index); // //find the frame // return (Image)gifImage.Clone(); // //return a copy of it } }
参考文章:
https://stackoverflow.com/questions/13485477/can-a-picturebox-show-animated-gif-in-windows-application
https://stackoverflow.com/questions/6576341/open-image-from-file-then-release-lock