winform图片查看器
1 、图片轮换浏览功能的实现
// 第一步
// 获得预览图片文件路径下的图片集合
public static List<string> GetImgCollection(string path)
{
string[] imgarray = Directory.GetFiles(path);
var result = from imgstring in imgarray
where imgstring.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
imgstring.EndsWith("png", StringComparison.OrdinalIgnoreCase)||
imgstring.EndsWith("bmp", StringComparison.OrdinalIgnoreCase)
select imgstring;
return result.ToList();
}
// 第二步
// 获得打开图片在图片集合中的索引
private int GetIndex(string imagepath)
{
int index = 0;
for (int i = 0; i < imgArray.Count; i++)
{
if (imgArray[i].Equals(imagepath))
{
index = i;
break;
}
}
return index;
}
// 切换图片的方法
private void SwitchImg(int index)
{
newbitmap = Image.FromFile(imgArray[index]);
picBoxView.Image = newbitmap;
imgPath = imgArray[index];
}
// 第三步
// 上一张图片
private void btnPre_Click(object sender, EventArgs e)
{
int index = GetIndex(imgPath);
// 释放上一张图片的资源,避免保存的时候出现ExternalException异常
newbitmap.Dispose();
if (index == 0)
{
SwitchImg(imgArray.Count - 1);
}
else
{
SwitchImg(index - 1);
}
}
// 下一张图片
private void btnNext_Click(object sender, EventArgs e)
{
int index = GetIndex(imgPath);
// 释放上一张图片的资源,避免保存的时候出现ExternalException异常
// 经常在调用Save方法的时候都会出现 一个GDI一般性错误,主要原因是文件没有被释放,当保存到原位置时,就会出现该异常,要避免这个错误就要释放图片占有的资源
newbitmap.Dispose();
if (index != imgArray.Count - 1)
{
SwitchImg(index + 1);
}
else
{
SwitchImg(0);
}
}
2 、图片旋转功能的实现
// 顺时针旋转90度旋转图片 private void btnRotate_Click(object sender, EventArgs e) { picBoxView.SizeMode = PictureBoxSizeMode.Zoom; // 顺时针旋转90度的另外一种实现 newbitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); picBoxView.Image = newbitmap; isRotate = true; //newbitmap = (Image)ImageManager.RotateImg(bitmap, 90f, Color.Transparent); ; //bitmap.Dispose(); //picBoxView.Image = newbitmap; } // 逆时针旋转90度 private void btncounterclockwiseRotate_Click(object sender, EventArgs e) { picBoxView.SizeMode = PictureBoxSizeMode.Zoom; // 逆时针旋转90度的另外实现 newbitmap.RotateFlip(RotateFlipType.Rotate270FlipNone); picBoxView.Image = newbitmap; isRotate = true; // 下面是旋转任意角度的代码 //newbitmap = (Image)ImageManager.RotateImg(bitmap, 360f-90f, Color.Transparent); ; //bitmap.Dispose(); //picBoxView.Image = newbitmap; }
3 、对旋转图片的保存功能的实现
// 关闭窗体后保存旋转后的图片到文件中
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (imgPath == null || isRotate == false)
{
return;
}
// 保存旋转后的图片
switch (Path.GetExtension(imgPath).ToLower())
{
case ".png":
newbitmap.Save(imgPath, ImageFormat.Png);
newbitmap.Dispose();
break;
case ".jpg":
newbitmap.Save(imgPath);
newbitmap.Dispose();
break;
default:
newbitmap.Save(imgPath, ImageFormat.Bmp);
newbitmap.Dispose();
break;
}
}
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号