当我使用以下代码将位图从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");
}
最佳答案
在您的函数中收到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 u。我已经使用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位图,并直接从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");
}
关于c# - 将8bpp转换为24bpp时图像被移位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13127171/