如何将"System.Drawing.Image"转换为"System.Drawing.Bitmap"? [英] How to Convert 'System.Drawing.Image' to 'System.Drawing.Bitmap'?
问题描述
GraphicsImage = new Bitmap(Panel1.Width, Panel1.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
openFileDialog1.Filter="JPEG|*.jpg";
GraphicsImage = Image.FromFile(openfiledialog1.FileName);
错误:
Error 1 Cannot implicitly convert type ''System.Drawing.Image'' to ''System.Drawing.Bitmap''. An explicit conversion exists (are you missing a cast?)
ERROR:
Error 1 Cannot implicitly convert type ''System.Drawing.Image'' to ''System.Drawing.Bitmap''. An explicit conversion exists (are you missing a cast?)
推荐答案
您必须使用以下内容更改最后一行
you have to change last line with following
GraphicsImage = (Bitmap)Image.FromFile(openfiledialog1.FileName);
这会更好,因为它们是相同的类型:
This would work better because they are the same type:
Bitmap graphicsImage = new Bitmap(Panel1.Width, Panel1.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
但是没有必要创建它,因为这样做时它会被前面两行覆盖:
But there is no need to create it because it is overwritten 2 lines ahead when doing:
GraphicsImage = Image.FromFile(openfiledialog1.FileName);
祝你好运!
Good luck!
错误消息中的内容完全正确.
您需要将图像投射到位图:
Exactly what the error message said.
You need to cast the Image to a Bitmap:
GraphicsImage = (Bitmap)Image.FromFile(openfiledialog1.FileName);
通过说显式强制转换存在",表明您必须进行类型强制转换.另一个说法是:
By saying that an "explicit casts exists" you''re hinted that you must do a type cast. Another verions is this:
GraphicsImage = Image.FromFile(openfiledialog1.FileName) as Bitmap;
修改:
如果要使图像适合面板,有两种选择:
1.保持图像的宽高比,您需要进行此调整
Modification:
You have two options if you want to make the image fit into the panel:
1. Keeping the images aspect ratio you need to make this adjustment
panel1.BackgroundImageLayout = ImageLayout.Zoom;
2.在不考虑图像高宽比的情况下,用图像填充整个面板
2. Filling the whole panel with the image disregarding the aspect ratio of the image
panel1.BackgroundImageLayout = ImageLayout.Stretch;
注意!
如果面板的尺寸与图像的尺寸不匹配,解决方案2将使您的图像失真.
最终修改
就这样!
干杯,
曼弗雷德(Manfred)
Caveat!
Solution 2 will leave you with a distorted image if the panel''s dimensions don''t match the dimensions of the image.
End Modification
That''s it!
Cheers,
Manfred
这篇关于如何将"System.Drawing.Image"转换为"System.Drawing.Bitmap"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!