当我使用下面的代码将位图从8bpp转换为24bpp时,结果图像被移位但我无法弄清楚原因,有人可以帮忙吗?
private static Bitmap ConvertTo24(Bitmap bmpIn)
{
bmpIn.Save(@"F:\sara1.bmp");
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
// Prevent DPI conversion
g.PageUnit = GraphicsUnit.Pixel;
// Draw the image
g.DrawImageUnscaled(bmpIn, 0, 0);
// g.DrawImage(bmpIn, 0, 0);
}
converted.Save(@"F:\sara2.bmp");
}
答案 0 :(得分:2)
以下代码对我有用:
private static Bitmap ConvertTo24(Bitmap bmpIn)
{
bmpIn.Save(@"F:\sara1.bmp");
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
// Prevent DPI conversion
g.PageUnit = GraphicsUnit.Pixel;
// Draw the image
// g.DrawImageUnscaled(bmpIn, 0, 0);
g.DrawImage(bmpIn, 0, 0, converted.Width, converted.Height);
}
converted.Save(@"F:\sara2.bmp");
}
提供宽度和高度可以重新调整图像。
答案 1 :(得分:1)
在您的功能中收到问题之前,bmpIn
可能会遇到问题。
将8bpp图像放入f:\sara1.bmp
之后,您可以测试以下(更好)代码(只是为了确保在转换前没有移动8bpp图像)。
private static Bitmap ConvertTo24(Bitmap bmpIn)
{
//Bitmap bmpIn;
bmpIn = new Bitmap(@"f:\sara1.bmp");
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
g.PageUnit = GraphicsUnit.Pixel;
Rectangle rng = new Rectangle(new Point(0, 0), bmpIn.Size);
g.DrawImage(bmpIn, rng); // use this instead of following
}
converted.Save(@"F:\sara2.bmp");
}
希望它工作正常4你。我在评论中已经使用了DrawImage(Image img,Rectangle rng)
答案已经完成。以下是解释。您的代码(已编辑。按原样使用并按照注释)
private static Bitmap ConvertTo24(Bitmap bmpIn)
{
bmpIn.Save(@"F:\sara1.bmp");
return;
// After you have called this function. Go open your image f:\sara1.bmp from
//hrad disk-- I doubt you would find it shifted here even before conversion
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
// Prevent DPI conversion
g.PageUnit = GraphicsUnit.Pixel;
// Draw the image
g.DrawImageUnscaled(bmpIn, 0, 0);
// g.DrawImage(bmpIn, 0, 0);
}
converted.Save(@"F:\sara2.bmp");
}
再次你的代码(我只是忽略你收到的8bpp Bitmap并直接从f驱动器中获取它,假设你在运行应用程序之前或者至少在调用此函数之前将其放入)
以下代码也适合我。
private static Bitmap ConvertTo24(Bitmap bmpIn)
{
Bitmap bmpIn = new Bitmap(@"f:\sara1.bmp");
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
// Prevent DPI conversion
g.PageUnit = GraphicsUnit.Pixel;
// Draw the image
g.DrawImageUnscaled(bmpIn, 0, 0);
// g.DrawImage(bmpIn, 0, 0);
}
converted.Save(@"F:\sara2.bmp");
}