绘图操作时报错“无法从带有索引像素格式的图像创建 Graphics 对象”

来源:互联网 发布:网易闪电邮 for mac 编辑:程序博客网 时间:2024/06/05 22:32

如下代码会出现“无法从带有索引像素格式的图像创建 Graphics 对象”异常

Bitmap bitmap = new Bitmap(fileName);

Graphics graphics = Graphics.FromImage(bitmap);

解决方法为DrawImage到一个空的图片。

            OpenFileDialog dialog = new OpenFileDialog            {                Filter = "Image|*.bmp;*.png;*.jpg;*.jpeg",                FilterIndex = 1            };            if (dialog.ShowDialog() == DialogResult.OK)            {                string fileName = dialog.FileName;                Bitmap bitmap = new Bitmap(dialog.FileName);                Bitmap image = new Bitmap(bitmap.Width, bitmap.Height);// 将原图片DrawImage到新图片image,然后在image上进行绘图操作                using (Graphics graphics = Graphics.FromImage(image))                {                    Rectangle destRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);                    Rectangle srcRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);                    graphics.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);                    graphics.Dispose();                }                Graphics graphicsNew = Graphics.FromImage(image);                Pen pen = new Pen(Color.Red);                graphicsNew.DrawRectangle(pen, 0, 0, image.Width - 3,image.Height - 3);// 在图片上绘制矩形框                this.pictureBox1.Image = image;            }


阅读全文
0 0