【问题标题】:Sometimes bitmaps are upside down when getting file thumbnails有时在获取文件缩略图时位图是颠倒的
【发布时间】:2013-07-25 01:18:00
【问题描述】:

我使用这种方法来获取文件的缩略图(保持透明度...):

public static Image GetIcon(string fileName, int size)
{
    IShellItem shellItem;
    Shell32.SHCreateItemFromParsingName(fileName, IntPtr.Zero, Shell32.IShellItem_GUID, out shellItem);

    IntPtr hbitmap;
    ((IShellItemImageFactory)shellItem).GetImage(new SIZE(size, size), 0x0, out hbitmap);

    // get the info about the HBITMAP inside the IPictureDisp
    DIBSECTION dibsection = new DIBSECTION();
    Gdi32.GetObjectDIBSection(hbitmap, Marshal.SizeOf(dibsection), ref dibsection);
    int width = dibsection.dsBm.bmWidth;
    int height = dibsection.dsBm.bmHeight;

    // create the destination Bitmap object
    Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);

    unsafe
    {
        // get a pointer to the raw bits
        RGBQUAD* pBits = (RGBQUAD*)(void*)dibsection.dsBm.bmBits;
        // copy each pixel manually
        for (int x = 0; x < dibsection.dsBmih.biWidth; x++)
        {
            for (int y = 0; y < dibsection.dsBmih.biHeight; y++)
            {
                int offset = y * dibsection.dsBmih.biWidth + x;
                if (pBits[offset].rgbReserved != 0)
                {
                    bitmap.SetPixel(x, y, Color.FromArgb(pBits[offset].rgbReserved, pBits[offset].rgbRed, pBits[offset].rgbGreen, pBits[offset].rgbBlue));
                }
            }
        }
    }
    Gdi32.DeleteObject(hbitmap);

    return bitmap;
}

但有时图像是颠倒的。当第二次、第三次获得相同的图像时,它不会倒置。有什么方法可以确定它是否颠倒?如果有任何解决方案,下面的代码应该可以工作:

if (isUpsideDown)
{
    int offset = (dibsection.dsBmih.biHeight - y - 1) * dibsection.dsBmih.biWidth + x;
}
else
{
    int offset = y * dibsection.dsBmih.biWidth + x;
}

【问题讨论】:

    标签: c# gdi hbitmap


    【解决方案1】:

    我遇到了同样的问题。剪贴板中的图像倒置。我设法发现,您可以检查 Stride 值以查看图像是否反转:

    BitmapData d = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
    bmp.UnlockBits(d);
    
    if (d.Stride > 0)
    {
        bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
    }
    

    如果 Stride 值大于零,则图像反转。

    安迪

    【讨论】:

      猜你喜欢
      • 2016-01-17
      • 2012-02-19
      • 2013-08-12
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2013-04-12
      相关资源
      最近更新 更多