G.drawimage 以不正确的尺寸绘制 [英] G.drawimage draws with incorrect size

查看:23
本文介绍了G.drawimage 以不正确的尺寸绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个大位图,其中包含来自文件的一些较小的图像.图像的大小均为 250 像素,但其中一个变小,另一个大于 250 像素.我只是使用基本的 g.drawimage 方法,所以我不明白我做错了什么.

Im creating a big bitmap which contains some smaller images from files. The images have both a size of 250px, but one of them gets smaller and the other bigger than 250px. I'm just using the basic g.drawimage method, so I don't get what I do wrong.

string[] imagePaths = Directory.GetFiles(@"C:UsersadminDesktopImages");
ArrayList images = new ArrayList();

foreach (var item in imagePaths)
    images.Add(new Bitmap(item, true));

Bitmap list = new Bitmap(840, 1188);

Graphics g = Graphics.FromImage(list);

int size = 0;

for (int i = 0; i < images.Count; i++)
{
    g.DrawImage((Bitmap)images[i], new Point(10, (i + 1) * 10 + size));
    Bitmap bmp = (Bitmap)images[i];
    Console.WriteLine(bmp.Height);
    Font drawFont = new Font("Arial", 16);
    size += bmp.Height;
    g.DrawString(imagePaths[i].Substring(imagePaths[i].LastIndexOf("\") + 1, imagePaths[i].Length - imagePaths[i].LastIndexOf("\") - 4), drawFont, Brushes.Black, new Point(bmp.Width + 30, (i + 1) * 10 + size / 4));
}    

list.Save(@"C:UsersadminDesktoplist.png", ImageFormat.Png);

推荐答案

您没有设置 dpi 值.这些在 DrawImage 中得到尊重,因此您需要使用 bitmap.SetResolution(dpix, dpiy) 设置它们.当它们在图像中不同时,结果也会不同.您可以从 Graphics 对象 g 中获得正确"的一个或决定您想要什么.

You don't set the dpi values. These are honored in DrawImage, so you need to set them with bitmap.SetResolution(dpix, dpiy). When they are different in the images the results will be too. You can get the 'correct' one from the Graphics object g or decide what you want.

快速修复:

        for (int i = 0; i < images.Count; i++)
        {
            ((Bitmap)images[i]).SetResolution(g.DpiX, g.DpiY);
            g.DrawImage((Bitmap)images[i], new Point(10, (i + 1) * 10 + size));
            Bitmap bmp = (Bitmap)images[i];
            ...
        }

请注意,新创建的位图使用屏幕 dpi 分辨率作为其默认值.如果你想控制 dpi,你还需要为 list 设置它们!

Note that the newly created bitmap uses the screen dpi resolution as its default. If you want to control the dpi you need to set them for list as well!

另请注意,我没有更改您的代码;为了简化最后​​一行应该真正移动到循环的顶部,然后使用 bmp 而不是数组元素..

Also note the I didn't change your code; to simplify the last line should really move to the top of the loop and then bmp be used instead of the array element..

这篇关于G.drawimage 以不正确的尺寸绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆