3

I use this method to get thumbnails of files (keeping transparency...):

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;
}

But sometimes the image is upside down. When getting the same image for 2nd, 3rd time it's not upside down. Is there any way to determine wether it is upside down or not? If there was any solution, the code below should work:

if (isUpsideDown)
{
    int offset = (dibsection.dsBmih.biHeight - y - 1) * dibsection.dsBmih.biWidth + x;
}
else
{
    int offset = y * dibsection.dsBmih.biWidth + x;
}
Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
Mart
  • 512
  • 5
  • 13

1 Answers1

0

I came across the same problem. Images from the clipboard where upside down. I managed to find out, that you can check the Stride value to see if the image is reversed:

BitmapData d = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
bmp.UnlockBits(d);

if (d.Stride > 0)
{
    bmp.RotateFlip(RotateFlipType.Rotate180FlipNone);
}

If the Stride value is greater than zero, the image is reversed.

Andy

DA.
  • 849
  • 6
  • 19