FileStream 打开图片的好处是读取图片到内存,保存为byte[],然后转为bitmap显示。这样被打开的图片资源不被占用。可以进行图片删除操作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace TransformTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.Filter = "Image Files (*.jpg;*.png;*.bmp;*gif;*.jpeg)|*.jpg;*.png;*.bmp;*.gif;*.jpeg";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imageData = new byte[br.BaseStream.Length];
int nRet = int.Parse(br.BaseStream.Length.ToString());
imageData = br.ReadBytes(nRet);
br.Close();
fs.Close();
Bitmap bitmapSource = BytesToBitmap(imageData);
pictureBox1.Image = bitmapSource;
Bitmap bitmap = KnockOutGzf(bitmapSource);
}
}
/// <summary>
/// 使用文件流打开文件转
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private Bitmap GetBitmap(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imageData = new byte[br.BaseStream.Length];
int nRet = int.Parse(br.BaseStream.Length.ToString());
imageData = br.ReadBytes(nRet);
br.Close();
fs.Close();
return BytesToBitmap(imageData);
}
/// <summary>
/// 去除白色背景色
/// </summary>
/// <param name="bitmapProxy"></param>
/// <returns></returns>
public System.Drawing.Bitmap KnockOutGzf(Bitmap bitmapProxy)
{
for (int i = 0; i < bitmapProxy.Width; i++)
{
for (int j = 0; j < bitmapProxy.Height; j++)
{
System.Drawing.Color c = bitmapProxy.GetPixel(i, j);
if (!(c.R < 240 || c.G < 240 || c.B < 240))
{
bitmapProxy.SetPixel(i, j, System.Drawing.Color.Transparent);
}
}
}
return bitmapProxy;
}
/// <summary>
/// byte[]数组转Bitmap
/// </summary>
/// <param name="Bytes"></param>
/// <returns></returns>
private System.Drawing.Bitmap BytesToBitmap(byte[] Bytes)
{
MemoryStream stream = null;
try
{
stream = new MemoryStream(Bytes);
return new System.Drawing.Bitmap((System.Drawing.Image)new System.Drawing.Bitmap(stream));
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
stream.Close();
}
}
}
}
项目代码地址,资源设置为0C币了。可以去下载。1.c#使用FileStream打开图片并显示。2.去除图片白色的背景色。-桌面系统文档类资源-CSDN下载