爱吃酸菜鱼的猫

对图片信息的处理

1.选择打开图片后,即获取到图片

private Bitmap bmp = null;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
//pbxShowImage.ImageLocation = ofd.FileName;
bmp = new Bitmap(ofd.FileName);
if (bmp == null)
{
MessageBox.Show("加载图片失败!", "错误");
return;
}
pbxShowImage.Image = bmp;
ofd.Dispose();
}
}

 

2. 获取图片里的信息,像素即宽、高,以及每个点的颜色信息。

private void button5_Click(object sender, EventArgs e)
{
ConvertTo8Byte(bmp);
}

public static unsafe byte[] ConvertTo8Byte(Bitmap img)
{

byte[] result = new byte[img.Width * img.Height];
int n = 0;
BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
var bp = (byte*)data.Scan0.ToPointer();

for (int i = 0; i != data.Height; i++)
{
for (int j = 0; j != data.Width; j++)
{
result[n] = bp[i * data.Stride + j * 3];
n++;
}
}
img.UnlockBits(data);
//img.Dispose();
return result;
}

 

3 改变宽、高,重新给图片赋值。可看到修改后的效果

private void btnSure_Click(object sender, EventArgs e)
{
Bitmap b= KiResizeImage(bmp, int.Parse(txtWidth.Text), int.Parse(txtHeight.Text));
pbxShowImage.Image = b;
}

public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH)
{
try
{
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
// 插值算法的质量
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch
{
return null;
}
}

 

4. 保存修改后的图片

private void button2_Click(object sender, EventArgs e)
{
if (bmp == null) return;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
pbxShowImage.Image.Save(sfd.FileName);
MessageBox.Show("保存成功!", "提示");
sfd.Dispose();
}
}

posted on 2018-04-26 10:31  爱吃酸菜鱼的猫  阅读(153)  评论(0编辑  收藏  举报

导航