oleaut32: Add a test for loading/saving an empty picture.
[wine] / dlls / gdiplus / image.c
1 /*
2  * Copyright (C) 2007 Google (Evan Stade)
3  * Copyright (C) 2012 Dmitry Timoshkov
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 #include <stdarg.h>
21 #include <assert.h>
22
23 #define NONAMELESSUNION
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winuser.h"
28 #include "wingdi.h"
29
30 #define COBJMACROS
31 #include "objbase.h"
32 #include "olectl.h"
33 #include "ole2.h"
34
35 #include "initguid.h"
36 #include "wincodec.h"
37 #include "gdiplus.h"
38 #include "gdiplus_private.h"
39 #include "wine/debug.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(gdiplus);
42
43 #define PIXELFORMATBPP(x) ((x) ? ((x) >> 8) & 255 : 24)
44
45 static const struct
46 {
47     const WICPixelFormatGUID *wic_format;
48     PixelFormat gdip_format;
49     /* predefined palette type to use for pixel format conversions */
50     WICBitmapPaletteType palette_type;
51 } pixel_formats[] =
52 {
53     { &GUID_WICPixelFormatBlackWhite, PixelFormat1bppIndexed, WICBitmapPaletteTypeFixedBW },
54     { &GUID_WICPixelFormat1bppIndexed, PixelFormat1bppIndexed, WICBitmapPaletteTypeFixedBW },
55     { &GUID_WICPixelFormat8bppGray, PixelFormat8bppIndexed, WICBitmapPaletteTypeFixedGray256 },
56     { &GUID_WICPixelFormat8bppIndexed, PixelFormat8bppIndexed, WICBitmapPaletteTypeFixedHalftone256 },
57     { &GUID_WICPixelFormat16bppBGR555, PixelFormat16bppRGB555, WICBitmapPaletteTypeFixedHalftone256 },
58     { &GUID_WICPixelFormat24bppBGR, PixelFormat24bppRGB, WICBitmapPaletteTypeFixedHalftone256 },
59     { &GUID_WICPixelFormat32bppBGR, PixelFormat32bppRGB, WICBitmapPaletteTypeFixedHalftone256 },
60     { &GUID_WICPixelFormat32bppBGRA, PixelFormat32bppARGB, WICBitmapPaletteTypeFixedHalftone256 },
61     { &GUID_WICPixelFormat32bppPBGRA, PixelFormat32bppPARGB, WICBitmapPaletteTypeFixedHalftone256 },
62     { NULL }
63 };
64
65 static ColorPalette *get_palette(IWICBitmapFrameDecode *frame, WICBitmapPaletteType palette_type)
66 {
67     HRESULT hr;
68     IWICImagingFactory *factory;
69     IWICPalette *wic_palette;
70     ColorPalette *palette = NULL;
71
72     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
73                           &IID_IWICImagingFactory, (void **)&factory);
74     if (hr != S_OK) return NULL;
75
76     hr = IWICImagingFactory_CreatePalette(factory, &wic_palette);
77     if (hr == S_OK)
78     {
79         hr = WINCODEC_ERR_PALETTEUNAVAILABLE;
80         if (frame)
81             hr = IWICBitmapFrameDecode_CopyPalette(frame, wic_palette);
82         if (hr != S_OK)
83         {
84             TRACE("using predefined palette %#x\n", palette_type);
85             hr = IWICPalette_InitializePredefined(wic_palette, palette_type, FALSE);
86         }
87         if (hr == S_OK)
88         {
89             UINT count;
90             BOOL mono, gray;
91
92             IWICPalette_IsBlackWhite(wic_palette, &mono);
93             IWICPalette_IsGrayscale(wic_palette, &gray);
94
95             IWICPalette_GetColorCount(wic_palette, &count);
96             palette = HeapAlloc(GetProcessHeap(), 0, 2 * sizeof(UINT) + count * sizeof(ARGB));
97             IWICPalette_GetColors(wic_palette, count, palette->Entries, &palette->Count);
98
99             if (mono)
100                 palette->Flags = 0;
101             else if (gray)
102                 palette->Flags = PaletteFlagsGrayScale;
103             else
104                 palette->Flags = PaletteFlagsHalftone;
105         }
106         IWICPalette_Release(wic_palette);
107     }
108     IWICImagingFactory_Release(factory);
109     return palette;
110 }
111
112 static INT ipicture_pixel_height(IPicture *pic)
113 {
114     HDC hdcref;
115     OLE_YSIZE_HIMETRIC y;
116
117     IPicture_get_Height(pic, &y);
118
119     hdcref = GetDC(0);
120
121     y = MulDiv(y, GetDeviceCaps(hdcref, LOGPIXELSY), INCH_HIMETRIC);
122     ReleaseDC(0, hdcref);
123
124     return y;
125 }
126
127 static INT ipicture_pixel_width(IPicture *pic)
128 {
129     HDC hdcref;
130     OLE_XSIZE_HIMETRIC x;
131
132     IPicture_get_Width(pic, &x);
133
134     hdcref = GetDC(0);
135
136     x = MulDiv(x, GetDeviceCaps(hdcref, LOGPIXELSX), INCH_HIMETRIC);
137
138     ReleaseDC(0, hdcref);
139
140     return x;
141 }
142
143 GpStatus WINGDIPAPI GdipBitmapApplyEffect(GpBitmap* bitmap, CGpEffect* effect,
144     RECT* roi, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
145 {
146     FIXME("(%p %p %p %d %p %p): stub\n", bitmap, effect, roi, useAuxData, auxData, auxDataSize);
147     /*
148      * Note: According to Jose Roca's GDI+ docs, this function is not
149      * implemented in Windows's GDI+.
150      */
151     return NotImplemented;
152 }
153
154 GpStatus WINGDIPAPI GdipBitmapCreateApplyEffect(GpBitmap** inputBitmaps,
155     INT numInputs, CGpEffect* effect, RECT* roi, RECT* outputRect,
156     GpBitmap** outputBitmap, BOOL useAuxData, VOID** auxData, INT* auxDataSize)
157 {
158     FIXME("(%p %d %p %p %p %p %d %p %p): stub\n", inputBitmaps, numInputs, effect, roi, outputRect, outputBitmap, useAuxData, auxData, auxDataSize);
159     /*
160      * Note: According to Jose Roca's GDI+ docs, this function is not
161      * implemented in Windows's GDI+.
162      */
163     return NotImplemented;
164 }
165
166 static inline void getpixel_1bppIndexed(BYTE *index, const BYTE *row, UINT x)
167 {
168     *index = (row[x/8]>>(7-x%8)) & 1;
169 }
170
171 static inline void getpixel_4bppIndexed(BYTE *index, const BYTE *row, UINT x)
172 {
173     if (x & 1)
174         *index = row[x/2]&0xf;
175     else
176         *index = row[x/2]>>4;
177 }
178
179 static inline void getpixel_8bppIndexed(BYTE *index, const BYTE *row, UINT x)
180 {
181     *index = row[x];
182 }
183
184 static inline void getpixel_16bppGrayScale(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
185     const BYTE *row, UINT x)
186 {
187     *r = *g = *b = row[x*2+1];
188     *a = 255;
189 }
190
191 static inline void getpixel_16bppRGB555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
192     const BYTE *row, UINT x)
193 {
194     WORD pixel = *((const WORD*)(row)+x);
195     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
196     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
197     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
198     *a = 255;
199 }
200
201 static inline void getpixel_16bppRGB565(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
202     const BYTE *row, UINT x)
203 {
204     WORD pixel = *((const WORD*)(row)+x);
205     *r = (pixel>>8&0xf8)|(pixel>>13&0x7);
206     *g = (pixel>>3&0xfc)|(pixel>>9&0x3);
207     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
208     *a = 255;
209 }
210
211 static inline void getpixel_16bppARGB1555(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
212     const BYTE *row, UINT x)
213 {
214     WORD pixel = *((const WORD*)(row)+x);
215     *r = (pixel>>7&0xf8)|(pixel>>12&0x7);
216     *g = (pixel>>2&0xf8)|(pixel>>6&0x7);
217     *b = (pixel<<3&0xf8)|(pixel>>2&0x7);
218     if ((pixel&0x8000) == 0x8000)
219         *a = 255;
220     else
221         *a = 0;
222 }
223
224 static inline void getpixel_24bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
225     const BYTE *row, UINT x)
226 {
227     *r = row[x*3+2];
228     *g = row[x*3+1];
229     *b = row[x*3];
230     *a = 255;
231 }
232
233 static inline void getpixel_32bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
234     const BYTE *row, UINT x)
235 {
236     *r = row[x*4+2];
237     *g = row[x*4+1];
238     *b = row[x*4];
239     *a = 255;
240 }
241
242 static inline void getpixel_32bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
243     const BYTE *row, UINT x)
244 {
245     *r = row[x*4+2];
246     *g = row[x*4+1];
247     *b = row[x*4];
248     *a = row[x*4+3];
249 }
250
251 static inline void getpixel_32bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
252     const BYTE *row, UINT x)
253 {
254     *a = row[x*4+3];
255     if (*a == 0)
256         *r = *g = *b = 0;
257     else
258     {
259         *r = row[x*4+2] * 255 / *a;
260         *g = row[x*4+1] * 255 / *a;
261         *b = row[x*4] * 255 / *a;
262     }
263 }
264
265 static inline void getpixel_48bppRGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
266     const BYTE *row, UINT x)
267 {
268     *r = row[x*6+5];
269     *g = row[x*6+3];
270     *b = row[x*6+1];
271     *a = 255;
272 }
273
274 static inline void getpixel_64bppARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
275     const BYTE *row, UINT x)
276 {
277     *r = row[x*8+5];
278     *g = row[x*8+3];
279     *b = row[x*8+1];
280     *a = row[x*8+7];
281 }
282
283 static inline void getpixel_64bppPARGB(BYTE *r, BYTE *g, BYTE *b, BYTE *a,
284     const BYTE *row, UINT x)
285 {
286     *a = row[x*8+7];
287     if (*a == 0)
288         *r = *g = *b = 0;
289     else
290     {
291         *r = row[x*8+5] * 255 / *a;
292         *g = row[x*8+3] * 255 / *a;
293         *b = row[x*8+1] * 255 / *a;
294     }
295 }
296
297 GpStatus WINGDIPAPI GdipBitmapGetPixel(GpBitmap* bitmap, INT x, INT y,
298     ARGB *color)
299 {
300     BYTE r, g, b, a;
301     BYTE index;
302     BYTE *row;
303     TRACE("%p %d %d %p\n", bitmap, x, y, color);
304
305     if(!bitmap || !color ||
306        x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
307         return InvalidParameter;
308
309     row = bitmap->bits+bitmap->stride*y;
310
311     switch (bitmap->format)
312     {
313         case PixelFormat1bppIndexed:
314             getpixel_1bppIndexed(&index,row,x);
315             break;
316         case PixelFormat4bppIndexed:
317             getpixel_4bppIndexed(&index,row,x);
318             break;
319         case PixelFormat8bppIndexed:
320             getpixel_8bppIndexed(&index,row,x);
321             break;
322         case PixelFormat16bppGrayScale:
323             getpixel_16bppGrayScale(&r,&g,&b,&a,row,x);
324             break;
325         case PixelFormat16bppRGB555:
326             getpixel_16bppRGB555(&r,&g,&b,&a,row,x);
327             break;
328         case PixelFormat16bppRGB565:
329             getpixel_16bppRGB565(&r,&g,&b,&a,row,x);
330             break;
331         case PixelFormat16bppARGB1555:
332             getpixel_16bppARGB1555(&r,&g,&b,&a,row,x);
333             break;
334         case PixelFormat24bppRGB:
335             getpixel_24bppRGB(&r,&g,&b,&a,row,x);
336             break;
337         case PixelFormat32bppRGB:
338             getpixel_32bppRGB(&r,&g,&b,&a,row,x);
339             break;
340         case PixelFormat32bppARGB:
341             getpixel_32bppARGB(&r,&g,&b,&a,row,x);
342             break;
343         case PixelFormat32bppPARGB:
344             getpixel_32bppPARGB(&r,&g,&b,&a,row,x);
345             break;
346         case PixelFormat48bppRGB:
347             getpixel_48bppRGB(&r,&g,&b,&a,row,x);
348             break;
349         case PixelFormat64bppARGB:
350             getpixel_64bppARGB(&r,&g,&b,&a,row,x);
351             break;
352         case PixelFormat64bppPARGB:
353             getpixel_64bppPARGB(&r,&g,&b,&a,row,x);
354             break;
355         default:
356             FIXME("not implemented for format 0x%x\n", bitmap->format);
357             return NotImplemented;
358     }
359
360     if (bitmap->format & PixelFormatIndexed)
361         *color = bitmap->image.palette->Entries[index];
362     else
363         *color = a<<24|r<<16|g<<8|b;
364
365     return Ok;
366 }
367
368 static inline UINT get_palette_index(BYTE r, BYTE g, BYTE b, BYTE a, ColorPalette *palette)
369 {
370     BYTE index = 0;
371     int best_distance = 0x7fff;
372     int distance;
373     int i;
374
375     if (!palette) return 0;
376     /* This algorithm scans entire palette,
377        computes difference from desired color (all color components have equal weight)
378        and returns the index of color with least difference.
379
380        Note: Maybe it could be replaced with a better algorithm for better image quality
381        and performance, though better algorithm would probably need some pre-built lookup
382        tables and thus may actually be slower if this method is called only few times per
383        every image.
384     */
385     for(i=0;i<palette->Count;i++) {
386         ARGB color=palette->Entries[i];
387         distance=abs(b-(color & 0xff)) + abs(g-(color>>8 & 0xff)) + abs(r-(color>>16 & 0xff)) + abs(a-(color>>24 & 0xff));
388         if (distance<best_distance) {
389             best_distance=distance;
390             index=i;
391         }
392     }
393     return index;
394 }
395
396 static inline void setpixel_8bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
397     BYTE *row, UINT x, ColorPalette *palette)
398 {
399      BYTE index = get_palette_index(r,g,b,a,palette);
400      row[x]=index;
401 }
402
403 static inline void setpixel_1bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
404     BYTE *row, UINT x, ColorPalette *palette)
405 {
406     row[x/8]  = (row[x/8] & ~(1<<(7-x%8))) | (get_palette_index(r,g,b,a,palette)<<(7-x%8));
407 }
408
409 static inline void setpixel_4bppIndexed(BYTE r, BYTE g, BYTE b, BYTE a,
410     BYTE *row, UINT x, ColorPalette *palette)
411 {
412     if (x & 1)
413         row[x/2] = (row[x/2] & 0xf0) | get_palette_index(r,g,b,a,palette);
414     else
415         row[x/2] = (row[x/2] & 0x0f) | get_palette_index(r,g,b,a,palette)<<4;
416 }
417
418 static inline void setpixel_16bppGrayScale(BYTE r, BYTE g, BYTE b, BYTE a,
419     BYTE *row, UINT x)
420 {
421     *((WORD*)(row)+x) = (r+g+b)*85;
422 }
423
424 static inline void setpixel_16bppRGB555(BYTE r, BYTE g, BYTE b, BYTE a,
425     BYTE *row, UINT x)
426 {
427     *((WORD*)(row)+x) = (r<<7&0x7c00)|
428                         (g<<2&0x03e0)|
429                         (b>>3&0x001f);
430 }
431
432 static inline void setpixel_16bppRGB565(BYTE r, BYTE g, BYTE b, BYTE a,
433     BYTE *row, UINT x)
434 {
435     *((WORD*)(row)+x) = (r<<8&0xf800)|
436                          (g<<3&0x07e0)|
437                          (b>>3&0x001f);
438 }
439
440 static inline void setpixel_16bppARGB1555(BYTE r, BYTE g, BYTE b, BYTE a,
441     BYTE *row, UINT x)
442 {
443     *((WORD*)(row)+x) = (a<<8&0x8000)|
444                         (r<<7&0x7c00)|
445                         (g<<2&0x03e0)|
446                         (b>>3&0x001f);
447 }
448
449 static inline void setpixel_24bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
450     BYTE *row, UINT x)
451 {
452     row[x*3+2] = r;
453     row[x*3+1] = g;
454     row[x*3] = b;
455 }
456
457 static inline void setpixel_32bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
458     BYTE *row, UINT x)
459 {
460     *((DWORD*)(row)+x) = (r<<16)|(g<<8)|b;
461 }
462
463 static inline void setpixel_32bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
464     BYTE *row, UINT x)
465 {
466     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
467 }
468
469 static inline void setpixel_32bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
470     BYTE *row, UINT x)
471 {
472     r = r * a / 255;
473     g = g * a / 255;
474     b = b * a / 255;
475     *((DWORD*)(row)+x) = (a<<24)|(r<<16)|(g<<8)|b;
476 }
477
478 static inline void setpixel_48bppRGB(BYTE r, BYTE g, BYTE b, BYTE a,
479     BYTE *row, UINT x)
480 {
481     row[x*6+5] = row[x*6+4] = r;
482     row[x*6+3] = row[x*6+2] = g;
483     row[x*6+1] = row[x*6] = b;
484 }
485
486 static inline void setpixel_64bppARGB(BYTE r, BYTE g, BYTE b, BYTE a,
487     BYTE *row, UINT x)
488 {
489     UINT64 a64=a, r64=r, g64=g, b64=b;
490     *((UINT64*)(row)+x) = (a64<<56)|(a64<<48)|(r64<<40)|(r64<<32)|(g64<<24)|(g64<<16)|(b64<<8)|b64;
491 }
492
493 static inline void setpixel_64bppPARGB(BYTE r, BYTE g, BYTE b, BYTE a,
494     BYTE *row, UINT x)
495 {
496     UINT64 a64, r64, g64, b64;
497     a64 = a * 257;
498     r64 = r * a / 255;
499     g64 = g * a / 255;
500     b64 = b * a / 255;
501     *((UINT64*)(row)+x) = (a64<<48)|(r64<<32)|(g64<<16)|b64;
502 }
503
504 GpStatus WINGDIPAPI GdipBitmapSetPixel(GpBitmap* bitmap, INT x, INT y,
505     ARGB color)
506 {
507     BYTE a, r, g, b;
508     BYTE *row;
509     TRACE("bitmap:%p, x:%d, y:%d, color:%08x\n", bitmap, x, y, color);
510
511     if(!bitmap || x < 0 || y < 0 || x >= bitmap->width || y >= bitmap->height)
512         return InvalidParameter;
513
514     a = color>>24;
515     r = color>>16;
516     g = color>>8;
517     b = color;
518
519     row = bitmap->bits + bitmap->stride * y;
520
521     switch (bitmap->format)
522     {
523         case PixelFormat16bppGrayScale:
524             setpixel_16bppGrayScale(r,g,b,a,row,x);
525             break;
526         case PixelFormat16bppRGB555:
527             setpixel_16bppRGB555(r,g,b,a,row,x);
528             break;
529         case PixelFormat16bppRGB565:
530             setpixel_16bppRGB565(r,g,b,a,row,x);
531             break;
532         case PixelFormat16bppARGB1555:
533             setpixel_16bppARGB1555(r,g,b,a,row,x);
534             break;
535         case PixelFormat24bppRGB:
536             setpixel_24bppRGB(r,g,b,a,row,x);
537             break;
538         case PixelFormat32bppRGB:
539             setpixel_32bppRGB(r,g,b,a,row,x);
540             break;
541         case PixelFormat32bppARGB:
542             setpixel_32bppARGB(r,g,b,a,row,x);
543             break;
544         case PixelFormat32bppPARGB:
545             setpixel_32bppPARGB(r,g,b,a,row,x);
546             break;
547         case PixelFormat48bppRGB:
548             setpixel_48bppRGB(r,g,b,a,row,x);
549             break;
550         case PixelFormat64bppARGB:
551             setpixel_64bppARGB(r,g,b,a,row,x);
552             break;
553         case PixelFormat64bppPARGB:
554             setpixel_64bppPARGB(r,g,b,a,row,x);
555             break;
556         case PixelFormat8bppIndexed:
557             setpixel_8bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
558             break;
559         case PixelFormat4bppIndexed:
560             setpixel_4bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
561             break;
562         case PixelFormat1bppIndexed:
563             setpixel_1bppIndexed(r,g,b,a,row,x,bitmap->image.palette);
564             break;
565         default:
566             FIXME("not implemented for format 0x%x\n", bitmap->format);
567             return NotImplemented;
568     }
569
570     return Ok;
571 }
572
573 GpStatus convert_pixels(INT width, INT height,
574     INT dst_stride, BYTE *dst_bits, PixelFormat dst_format,
575     INT src_stride, const BYTE *src_bits, PixelFormat src_format,
576     ColorPalette *palette)
577 {
578     INT x, y;
579
580     if (src_format == dst_format ||
581         (dst_format == PixelFormat32bppRGB && PIXELFORMATBPP(src_format) == 32))
582     {
583         UINT widthbytes = PIXELFORMATBPP(src_format) * width / 8;
584         for (y=0; y<height; y++)
585             memcpy(dst_bits+dst_stride*y, src_bits+src_stride*y, widthbytes);
586         return Ok;
587     }
588
589 #define convert_indexed_to_rgb(getpixel_function, setpixel_function) do { \
590     for (x=0; x<width; x++) \
591         for (y=0; y<height; y++) { \
592             BYTE index; \
593             ARGB argb; \
594             BYTE *color = (BYTE *)&argb; \
595             getpixel_function(&index, src_bits+src_stride*y, x); \
596             argb = (palette && index < palette->Count) ? palette->Entries[index] : 0; \
597             setpixel_function(color[2], color[1], color[0], color[3], dst_bits+dst_stride*y, x); \
598         } \
599     return Ok; \
600 } while (0);
601
602 #define convert_rgb_to_rgb(getpixel_function, setpixel_function) do { \
603     for (x=0; x<width; x++) \
604         for (y=0; y<height; y++) { \
605             BYTE r, g, b, a; \
606             getpixel_function(&r, &g, &b, &a, src_bits+src_stride*y, x); \
607             setpixel_function(r, g, b, a, dst_bits+dst_stride*y, x); \
608         } \
609     return Ok; \
610 } while (0);
611
612 #define convert_rgb_to_indexed(getpixel_function, setpixel_function) do { \
613     for (x=0; x<width; x++) \
614         for (y=0; y<height; y++) { \
615             BYTE r, g, b, a; \
616             getpixel_function(&r, &g, &b, &a, src_bits+src_stride*y, x); \
617             setpixel_function(r, g, b, a, dst_bits+dst_stride*y, x, palette); \
618         } \
619     return Ok; \
620 } while (0);
621
622     switch (src_format)
623     {
624     case PixelFormat1bppIndexed:
625         switch (dst_format)
626         {
627         case PixelFormat16bppGrayScale:
628             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppGrayScale);
629         case PixelFormat16bppRGB555:
630             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppRGB555);
631         case PixelFormat16bppRGB565:
632             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppRGB565);
633         case PixelFormat16bppARGB1555:
634             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_16bppARGB1555);
635         case PixelFormat24bppRGB:
636             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_24bppRGB);
637         case PixelFormat32bppRGB:
638             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppRGB);
639         case PixelFormat32bppARGB:
640             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppARGB);
641         case PixelFormat32bppPARGB:
642             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_32bppPARGB);
643         case PixelFormat48bppRGB:
644             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_48bppRGB);
645         case PixelFormat64bppARGB:
646             convert_indexed_to_rgb(getpixel_1bppIndexed, setpixel_64bppARGB);
647         default:
648             break;
649         }
650         break;
651     case PixelFormat4bppIndexed:
652         switch (dst_format)
653         {
654         case PixelFormat16bppGrayScale:
655             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppGrayScale);
656         case PixelFormat16bppRGB555:
657             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppRGB555);
658         case PixelFormat16bppRGB565:
659             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppRGB565);
660         case PixelFormat16bppARGB1555:
661             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_16bppARGB1555);
662         case PixelFormat24bppRGB:
663             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_24bppRGB);
664         case PixelFormat32bppRGB:
665             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppRGB);
666         case PixelFormat32bppARGB:
667             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppARGB);
668         case PixelFormat32bppPARGB:
669             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_32bppPARGB);
670         case PixelFormat48bppRGB:
671             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_48bppRGB);
672         case PixelFormat64bppARGB:
673             convert_indexed_to_rgb(getpixel_4bppIndexed, setpixel_64bppARGB);
674         default:
675             break;
676         }
677         break;
678     case PixelFormat8bppIndexed:
679         switch (dst_format)
680         {
681         case PixelFormat16bppGrayScale:
682             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppGrayScale);
683         case PixelFormat16bppRGB555:
684             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppRGB555);
685         case PixelFormat16bppRGB565:
686             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppRGB565);
687         case PixelFormat16bppARGB1555:
688             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_16bppARGB1555);
689         case PixelFormat24bppRGB:
690             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_24bppRGB);
691         case PixelFormat32bppRGB:
692             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppRGB);
693         case PixelFormat32bppARGB:
694             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppARGB);
695         case PixelFormat32bppPARGB:
696             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_32bppPARGB);
697         case PixelFormat48bppRGB:
698             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_48bppRGB);
699         case PixelFormat64bppARGB:
700             convert_indexed_to_rgb(getpixel_8bppIndexed, setpixel_64bppARGB);
701         default:
702             break;
703         }
704         break;
705     case PixelFormat16bppGrayScale:
706         switch (dst_format)
707         {
708         case PixelFormat1bppIndexed:
709             convert_rgb_to_indexed(getpixel_16bppGrayScale, setpixel_1bppIndexed);
710         case PixelFormat8bppIndexed:
711             convert_rgb_to_indexed(getpixel_16bppGrayScale, setpixel_8bppIndexed);
712         case PixelFormat16bppRGB555:
713             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppRGB555);
714         case PixelFormat16bppRGB565:
715             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppRGB565);
716         case PixelFormat16bppARGB1555:
717             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_16bppARGB1555);
718         case PixelFormat24bppRGB:
719             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_24bppRGB);
720         case PixelFormat32bppRGB:
721             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppRGB);
722         case PixelFormat32bppARGB:
723             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppARGB);
724         case PixelFormat32bppPARGB:
725             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_32bppPARGB);
726         case PixelFormat48bppRGB:
727             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_48bppRGB);
728         case PixelFormat64bppARGB:
729             convert_rgb_to_rgb(getpixel_16bppGrayScale, setpixel_64bppARGB);
730         default:
731             break;
732         }
733         break;
734     case PixelFormat16bppRGB555:
735         switch (dst_format)
736         {
737         case PixelFormat1bppIndexed:
738             convert_rgb_to_indexed(getpixel_16bppRGB555, setpixel_1bppIndexed);
739         case PixelFormat8bppIndexed:
740             convert_rgb_to_indexed(getpixel_16bppRGB555, setpixel_8bppIndexed);
741         case PixelFormat16bppGrayScale:
742             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppGrayScale);
743         case PixelFormat16bppRGB565:
744             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppRGB565);
745         case PixelFormat16bppARGB1555:
746             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_16bppARGB1555);
747         case PixelFormat24bppRGB:
748             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_24bppRGB);
749         case PixelFormat32bppRGB:
750             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppRGB);
751         case PixelFormat32bppARGB:
752             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppARGB);
753         case PixelFormat32bppPARGB:
754             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_32bppPARGB);
755         case PixelFormat48bppRGB:
756             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_48bppRGB);
757         case PixelFormat64bppARGB:
758             convert_rgb_to_rgb(getpixel_16bppRGB555, setpixel_64bppARGB);
759         default:
760             break;
761         }
762         break;
763     case PixelFormat16bppRGB565:
764         switch (dst_format)
765         {
766         case PixelFormat1bppIndexed:
767             convert_rgb_to_indexed(getpixel_16bppRGB565, setpixel_1bppIndexed);
768         case PixelFormat8bppIndexed:
769             convert_rgb_to_indexed(getpixel_16bppRGB565, setpixel_8bppIndexed);
770         case PixelFormat16bppGrayScale:
771             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppGrayScale);
772         case PixelFormat16bppRGB555:
773             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppRGB555);
774         case PixelFormat16bppARGB1555:
775             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_16bppARGB1555);
776         case PixelFormat24bppRGB:
777             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_24bppRGB);
778         case PixelFormat32bppRGB:
779             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppRGB);
780         case PixelFormat32bppARGB:
781             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppARGB);
782         case PixelFormat32bppPARGB:
783             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_32bppPARGB);
784         case PixelFormat48bppRGB:
785             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_48bppRGB);
786         case PixelFormat64bppARGB:
787             convert_rgb_to_rgb(getpixel_16bppRGB565, setpixel_64bppARGB);
788         default:
789             break;
790         }
791         break;
792     case PixelFormat16bppARGB1555:
793         switch (dst_format)
794         {
795         case PixelFormat1bppIndexed:
796             convert_rgb_to_indexed(getpixel_16bppARGB1555, setpixel_1bppIndexed);
797         case PixelFormat8bppIndexed:
798             convert_rgb_to_indexed(getpixel_16bppARGB1555, setpixel_8bppIndexed);
799         case PixelFormat16bppGrayScale:
800             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppGrayScale);
801         case PixelFormat16bppRGB555:
802             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppRGB555);
803         case PixelFormat16bppRGB565:
804             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_16bppRGB565);
805         case PixelFormat24bppRGB:
806             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_24bppRGB);
807         case PixelFormat32bppRGB:
808             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppRGB);
809         case PixelFormat32bppARGB:
810             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppARGB);
811         case PixelFormat32bppPARGB:
812             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_32bppPARGB);
813         case PixelFormat48bppRGB:
814             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_48bppRGB);
815         case PixelFormat64bppARGB:
816             convert_rgb_to_rgb(getpixel_16bppARGB1555, setpixel_64bppARGB);
817         default:
818             break;
819         }
820         break;
821     case PixelFormat24bppRGB:
822         switch (dst_format)
823         {
824         case PixelFormat1bppIndexed:
825             convert_rgb_to_indexed(getpixel_24bppRGB, setpixel_1bppIndexed);
826         case PixelFormat8bppIndexed:
827             convert_rgb_to_indexed(getpixel_24bppRGB, setpixel_8bppIndexed);
828         case PixelFormat16bppGrayScale:
829             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppGrayScale);
830         case PixelFormat16bppRGB555:
831             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppRGB555);
832         case PixelFormat16bppRGB565:
833             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppRGB565);
834         case PixelFormat16bppARGB1555:
835             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_16bppARGB1555);
836         case PixelFormat32bppRGB:
837             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppRGB);
838         case PixelFormat32bppARGB:
839             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppARGB);
840         case PixelFormat32bppPARGB:
841             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_32bppPARGB);
842         case PixelFormat48bppRGB:
843             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_48bppRGB);
844         case PixelFormat64bppARGB:
845             convert_rgb_to_rgb(getpixel_24bppRGB, setpixel_64bppARGB);
846         default:
847             break;
848         }
849         break;
850     case PixelFormat32bppRGB:
851         switch (dst_format)
852         {
853         case PixelFormat1bppIndexed:
854             convert_rgb_to_indexed(getpixel_32bppRGB, setpixel_1bppIndexed);
855         case PixelFormat8bppIndexed:
856             convert_rgb_to_indexed(getpixel_32bppRGB, setpixel_8bppIndexed);
857         case PixelFormat16bppGrayScale:
858             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppGrayScale);
859         case PixelFormat16bppRGB555:
860             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppRGB555);
861         case PixelFormat16bppRGB565:
862             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppRGB565);
863         case PixelFormat16bppARGB1555:
864             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_16bppARGB1555);
865         case PixelFormat24bppRGB:
866             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_24bppRGB);
867         case PixelFormat32bppARGB:
868             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_32bppARGB);
869         case PixelFormat32bppPARGB:
870             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_32bppPARGB);
871         case PixelFormat48bppRGB:
872             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_48bppRGB);
873         case PixelFormat64bppARGB:
874             convert_rgb_to_rgb(getpixel_32bppRGB, setpixel_64bppARGB);
875         default:
876             break;
877         }
878         break;
879     case PixelFormat32bppARGB:
880         switch (dst_format)
881         {
882         case PixelFormat1bppIndexed:
883             convert_rgb_to_indexed(getpixel_32bppARGB, setpixel_1bppIndexed);
884         case PixelFormat8bppIndexed:
885             convert_rgb_to_indexed(getpixel_32bppARGB, setpixel_8bppIndexed);
886         case PixelFormat16bppGrayScale:
887             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppGrayScale);
888         case PixelFormat16bppRGB555:
889             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppRGB555);
890         case PixelFormat16bppRGB565:
891             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppRGB565);
892         case PixelFormat16bppARGB1555:
893             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_16bppARGB1555);
894         case PixelFormat24bppRGB:
895             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_24bppRGB);
896         case PixelFormat32bppPARGB:
897             convert_32bppARGB_to_32bppPARGB(width, height, dst_bits, dst_stride, src_bits, src_stride);
898             return Ok;
899         case PixelFormat48bppRGB:
900             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_48bppRGB);
901         case PixelFormat64bppARGB:
902             convert_rgb_to_rgb(getpixel_32bppARGB, setpixel_64bppARGB);
903         default:
904             break;
905         }
906         break;
907     case PixelFormat32bppPARGB:
908         switch (dst_format)
909         {
910         case PixelFormat1bppIndexed:
911             convert_rgb_to_indexed(getpixel_32bppPARGB, setpixel_1bppIndexed);
912         case PixelFormat8bppIndexed:
913             convert_rgb_to_indexed(getpixel_32bppPARGB, setpixel_8bppIndexed);
914         case PixelFormat16bppGrayScale:
915             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppGrayScale);
916         case PixelFormat16bppRGB555:
917             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppRGB555);
918         case PixelFormat16bppRGB565:
919             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppRGB565);
920         case PixelFormat16bppARGB1555:
921             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_16bppARGB1555);
922         case PixelFormat24bppRGB:
923             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_24bppRGB);
924         case PixelFormat32bppRGB:
925             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_32bppRGB);
926         case PixelFormat32bppARGB:
927             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_32bppARGB);
928         case PixelFormat48bppRGB:
929             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_48bppRGB);
930         case PixelFormat64bppARGB:
931             convert_rgb_to_rgb(getpixel_32bppPARGB, setpixel_64bppARGB);
932         default:
933             break;
934         }
935         break;
936     case PixelFormat48bppRGB:
937         switch (dst_format)
938         {
939         case PixelFormat1bppIndexed:
940             convert_rgb_to_indexed(getpixel_48bppRGB, setpixel_1bppIndexed);
941         case PixelFormat8bppIndexed:
942             convert_rgb_to_indexed(getpixel_48bppRGB, setpixel_8bppIndexed);
943         case PixelFormat16bppGrayScale:
944             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppGrayScale);
945         case PixelFormat16bppRGB555:
946             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppRGB555);
947         case PixelFormat16bppRGB565:
948             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppRGB565);
949         case PixelFormat16bppARGB1555:
950             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_16bppARGB1555);
951         case PixelFormat24bppRGB:
952             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_24bppRGB);
953         case PixelFormat32bppRGB:
954             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppRGB);
955         case PixelFormat32bppARGB:
956             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppARGB);
957         case PixelFormat32bppPARGB:
958             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_32bppPARGB);
959         case PixelFormat64bppARGB:
960             convert_rgb_to_rgb(getpixel_48bppRGB, setpixel_64bppARGB);
961         default:
962             break;
963         }
964         break;
965     case PixelFormat64bppARGB:
966         switch (dst_format)
967         {
968         case PixelFormat1bppIndexed:
969             convert_rgb_to_indexed(getpixel_64bppARGB, setpixel_1bppIndexed);
970         case PixelFormat8bppIndexed:
971             convert_rgb_to_indexed(getpixel_64bppARGB, setpixel_8bppIndexed);
972         case PixelFormat16bppGrayScale:
973             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppGrayScale);
974         case PixelFormat16bppRGB555:
975             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppRGB555);
976         case PixelFormat16bppRGB565:
977             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppRGB565);
978         case PixelFormat16bppARGB1555:
979             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_16bppARGB1555);
980         case PixelFormat24bppRGB:
981             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_24bppRGB);
982         case PixelFormat32bppRGB:
983             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppRGB);
984         case PixelFormat32bppARGB:
985             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppARGB);
986         case PixelFormat32bppPARGB:
987             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_32bppPARGB);
988         case PixelFormat48bppRGB:
989             convert_rgb_to_rgb(getpixel_64bppARGB, setpixel_48bppRGB);
990         default:
991             break;
992         }
993         break;
994     case PixelFormat64bppPARGB:
995         switch (dst_format)
996         {
997         case PixelFormat1bppIndexed:
998             convert_rgb_to_indexed(getpixel_64bppPARGB, setpixel_1bppIndexed);
999         case PixelFormat8bppIndexed:
1000             convert_rgb_to_indexed(getpixel_64bppPARGB, setpixel_8bppIndexed);
1001         case PixelFormat16bppGrayScale:
1002             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppGrayScale);
1003         case PixelFormat16bppRGB555:
1004             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppRGB555);
1005         case PixelFormat16bppRGB565:
1006             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppRGB565);
1007         case PixelFormat16bppARGB1555:
1008             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_16bppARGB1555);
1009         case PixelFormat24bppRGB:
1010             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_24bppRGB);
1011         case PixelFormat32bppRGB:
1012             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppRGB);
1013         case PixelFormat32bppARGB:
1014             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppARGB);
1015         case PixelFormat32bppPARGB:
1016             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_32bppPARGB);
1017         case PixelFormat48bppRGB:
1018             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_48bppRGB);
1019         case PixelFormat64bppARGB:
1020             convert_rgb_to_rgb(getpixel_64bppPARGB, setpixel_64bppARGB);
1021         default:
1022             break;
1023         }
1024         break;
1025     default:
1026         break;
1027     }
1028
1029 #undef convert_indexed_to_rgb
1030 #undef convert_rgb_to_rgb
1031
1032     return NotImplemented;
1033 }
1034
1035 /* This function returns a pointer to an array of pixels that represents the
1036  * bitmap. The *entire* bitmap is locked according to the lock mode specified by
1037  * flags.  It is correct behavior that a user who calls this function with write
1038  * privileges can write to the whole bitmap (not just the area in rect).
1039  *
1040  * FIXME: only used portion of format is bits per pixel. */
1041 GpStatus WINGDIPAPI GdipBitmapLockBits(GpBitmap* bitmap, GDIPCONST GpRect* rect,
1042     UINT flags, PixelFormat format, BitmapData* lockeddata)
1043 {
1044     INT bitspp = PIXELFORMATBPP(format);
1045     GpRect act_rect; /* actual rect to be used */
1046     GpStatus stat;
1047
1048     TRACE("%p %p %d 0x%x %p\n", bitmap, rect, flags, format, lockeddata);
1049
1050     if(!lockeddata || !bitmap)
1051         return InvalidParameter;
1052
1053     if(rect){
1054         if(rect->X < 0 || rect->Y < 0 || (rect->X + rect->Width > bitmap->width) ||
1055           (rect->Y + rect->Height > bitmap->height) || !flags)
1056             return InvalidParameter;
1057
1058         act_rect = *rect;
1059     }
1060     else{
1061         act_rect.X = act_rect.Y = 0;
1062         act_rect.Width  = bitmap->width;
1063         act_rect.Height = bitmap->height;
1064     }
1065
1066     if(bitmap->lockmode)
1067     {
1068         WARN("bitmap is already locked and cannot be locked again\n");
1069         return WrongState;
1070     }
1071
1072     if (bitmap->bits && bitmap->format == format && !(flags & ImageLockModeUserInputBuf))
1073     {
1074         /* no conversion is necessary; just use the bits directly */
1075         lockeddata->Width = act_rect.Width;
1076         lockeddata->Height = act_rect.Height;
1077         lockeddata->PixelFormat = format;
1078         lockeddata->Reserved = flags;
1079         lockeddata->Stride = bitmap->stride;
1080         lockeddata->Scan0 = bitmap->bits + (bitspp / 8) * act_rect.X +
1081                             bitmap->stride * act_rect.Y;
1082
1083         bitmap->lockmode = flags | ImageLockModeRead;
1084         bitmap->numlocks++;
1085
1086         return Ok;
1087     }
1088
1089     /* Make sure we can convert to the requested format. */
1090     if (flags & ImageLockModeRead)
1091     {
1092         stat = convert_pixels(0, 0, 0, NULL, format, 0, NULL, bitmap->format, NULL);
1093         if (stat == NotImplemented)
1094         {
1095             FIXME("cannot read bitmap from %x to %x\n", bitmap->format, format);
1096             return NotImplemented;
1097         }
1098     }
1099
1100     /* If we're opening for writing, make sure we'll be able to write back in
1101      * the original format. */
1102     if (flags & ImageLockModeWrite)
1103     {
1104         stat = convert_pixels(0, 0, 0, NULL, bitmap->format, 0, NULL, format, NULL);
1105         if (stat == NotImplemented)
1106         {
1107             FIXME("cannot write bitmap from %x to %x\n", format, bitmap->format);
1108             return NotImplemented;
1109         }
1110     }
1111
1112     lockeddata->Width  = act_rect.Width;
1113     lockeddata->Height = act_rect.Height;
1114     lockeddata->PixelFormat = format;
1115     lockeddata->Reserved = flags;
1116
1117     if(!(flags & ImageLockModeUserInputBuf))
1118     {
1119         lockeddata->Stride = (((act_rect.Width * bitspp + 7) / 8) + 3) & ~3;
1120
1121         bitmap->bitmapbits = GdipAlloc(lockeddata->Stride * act_rect.Height);
1122
1123         if (!bitmap->bitmapbits) return OutOfMemory;
1124
1125         lockeddata->Scan0  = bitmap->bitmapbits;
1126     }
1127
1128     if (flags & ImageLockModeRead)
1129     {
1130         static int fixme=0;
1131
1132         if (!fixme && (PIXELFORMATBPP(bitmap->format) * act_rect.X) % 8 != 0)
1133         {
1134             FIXME("Cannot copy rows that don't start at a whole byte.\n");
1135             fixme = 1;
1136         }
1137
1138         stat = convert_pixels(act_rect.Width, act_rect.Height,
1139             lockeddata->Stride, lockeddata->Scan0, format,
1140             bitmap->stride,
1141             bitmap->bits + bitmap->stride * act_rect.Y + PIXELFORMATBPP(bitmap->format) * act_rect.X / 8,
1142             bitmap->format, bitmap->image.palette);
1143
1144         if (stat != Ok)
1145         {
1146             GdipFree(bitmap->bitmapbits);
1147             bitmap->bitmapbits = NULL;
1148             return stat;
1149         }
1150     }
1151
1152     bitmap->lockmode = flags | ImageLockModeRead;
1153     bitmap->numlocks++;
1154     bitmap->lockx = act_rect.X;
1155     bitmap->locky = act_rect.Y;
1156
1157     return Ok;
1158 }
1159
1160 GpStatus WINGDIPAPI GdipBitmapSetResolution(GpBitmap* bitmap, REAL xdpi, REAL ydpi)
1161 {
1162     TRACE("(%p, %.2f, %.2f)\n", bitmap, xdpi, ydpi);
1163
1164     if (!bitmap || xdpi == 0.0 || ydpi == 0.0)
1165         return InvalidParameter;
1166
1167     bitmap->image.xres = xdpi;
1168     bitmap->image.yres = ydpi;
1169
1170     return Ok;
1171 }
1172
1173 GpStatus WINGDIPAPI GdipBitmapUnlockBits(GpBitmap* bitmap,
1174     BitmapData* lockeddata)
1175 {
1176     GpStatus stat;
1177     static int fixme=0;
1178
1179     TRACE("(%p,%p)\n", bitmap, lockeddata);
1180
1181     if(!bitmap || !lockeddata)
1182         return InvalidParameter;
1183
1184     if(!bitmap->lockmode)
1185         return WrongState;
1186
1187     if(!(lockeddata->Reserved & ImageLockModeWrite)){
1188         if(!(--bitmap->numlocks))
1189             bitmap->lockmode = 0;
1190
1191         GdipFree(bitmap->bitmapbits);
1192         bitmap->bitmapbits = NULL;
1193         return Ok;
1194     }
1195
1196     if (!bitmap->bitmapbits && !(lockeddata->Reserved & ImageLockModeUserInputBuf))
1197     {
1198         /* we passed a direct reference; no need to do anything */
1199         bitmap->lockmode = 0;
1200         bitmap->numlocks = 0;
1201         return Ok;
1202     }
1203
1204     if (!fixme && (PIXELFORMATBPP(bitmap->format) * bitmap->lockx) % 8 != 0)
1205     {
1206         FIXME("Cannot copy rows that don't start at a whole byte.\n");
1207         fixme = 1;
1208     }
1209
1210     stat = convert_pixels(lockeddata->Width, lockeddata->Height,
1211         bitmap->stride,
1212         bitmap->bits + bitmap->stride * bitmap->locky + PIXELFORMATBPP(bitmap->format) * bitmap->lockx / 8,
1213         bitmap->format,
1214         lockeddata->Stride, lockeddata->Scan0, lockeddata->PixelFormat, NULL);
1215
1216     if (stat != Ok)
1217     {
1218         ERR("failed to convert pixels; this should never happen\n");
1219     }
1220
1221     GdipFree(bitmap->bitmapbits);
1222     bitmap->bitmapbits = NULL;
1223     bitmap->lockmode = 0;
1224     bitmap->numlocks = 0;
1225
1226     return stat;
1227 }
1228
1229 GpStatus WINGDIPAPI GdipCloneBitmapArea(REAL x, REAL y, REAL width, REAL height,
1230     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
1231 {
1232     BitmapData lockeddata_src, lockeddata_dst;
1233     int i;
1234     UINT row_size;
1235     Rect area;
1236     GpStatus stat;
1237
1238     TRACE("(%f,%f,%f,%f,0x%x,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
1239
1240     if (!srcBitmap || !dstBitmap || srcBitmap->image.type != ImageTypeBitmap ||
1241         x < 0 || y < 0 ||
1242         x + width > srcBitmap->width || y + height > srcBitmap->height)
1243     {
1244         TRACE("<-- InvalidParameter\n");
1245         return InvalidParameter;
1246     }
1247
1248     if (format == PixelFormatDontCare)
1249         format = srcBitmap->format;
1250
1251     area.X = gdip_round(x);
1252     area.Y = gdip_round(y);
1253     area.Width = gdip_round(width);
1254     area.Height = gdip_round(height);
1255
1256     stat = GdipBitmapLockBits(srcBitmap, &area, ImageLockModeRead, format,
1257         &lockeddata_src);
1258     if (stat != Ok) return stat;
1259
1260     stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
1261         0, lockeddata_src.PixelFormat, NULL, dstBitmap);
1262     if (stat == Ok)
1263     {
1264         stat = GdipBitmapLockBits(*dstBitmap, NULL, ImageLockModeWrite,
1265             lockeddata_src.PixelFormat, &lockeddata_dst);
1266
1267         if (stat == Ok)
1268         {
1269             /* copy the image data */
1270             row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
1271             for (i=0; i<lockeddata_src.Height; i++)
1272                 memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
1273                        (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
1274                        row_size);
1275
1276             GdipBitmapUnlockBits(*dstBitmap, &lockeddata_dst);
1277         }
1278
1279         if (stat != Ok)
1280             GdipDisposeImage((GpImage*)*dstBitmap);
1281     }
1282
1283     GdipBitmapUnlockBits(srcBitmap, &lockeddata_src);
1284
1285     if (stat != Ok)
1286     {
1287         *dstBitmap = NULL;
1288     }
1289
1290     return stat;
1291 }
1292
1293 GpStatus WINGDIPAPI GdipCloneBitmapAreaI(INT x, INT y, INT width, INT height,
1294     PixelFormat format, GpBitmap* srcBitmap, GpBitmap** dstBitmap)
1295 {
1296     TRACE("(%i,%i,%i,%i,0x%x,%p,%p)\n", x, y, width, height, format, srcBitmap, dstBitmap);
1297
1298     return GdipCloneBitmapArea(x, y, width, height, format, srcBitmap, dstBitmap);
1299 }
1300
1301 GpStatus WINGDIPAPI GdipCloneImage(GpImage *image, GpImage **cloneImage)
1302 {
1303     GpStatus stat = GenericError;
1304
1305     TRACE("%p, %p\n", image, cloneImage);
1306
1307     if (!image || !cloneImage)
1308         return InvalidParameter;
1309
1310     if (image->picture)
1311     {
1312         IStream* stream;
1313         HRESULT hr;
1314         INT size;
1315         LARGE_INTEGER move;
1316
1317         hr = CreateStreamOnHGlobal(0, TRUE, &stream);
1318         if (FAILED(hr))
1319             return GenericError;
1320
1321         hr = IPicture_SaveAsFile(image->picture, stream, FALSE, &size);
1322         if(FAILED(hr))
1323         {
1324             WARN("Failed to save image on stream\n");
1325             goto out;
1326         }
1327
1328         /* Set seek pointer back to the beginning of the picture */
1329         move.QuadPart = 0;
1330         hr = IStream_Seek(stream, move, STREAM_SEEK_SET, NULL);
1331         if (FAILED(hr))
1332             goto out;
1333
1334         stat = GdipLoadImageFromStream(stream, cloneImage);
1335         if (stat != Ok) WARN("Failed to load image from stream\n");
1336
1337     out:
1338         IStream_Release(stream);
1339         return stat;
1340     }
1341     else if (image->type == ImageTypeBitmap)
1342     {
1343         GpBitmap *bitmap = (GpBitmap*)image;
1344         BitmapData lockeddata_src, lockeddata_dst;
1345         int i;
1346         UINT row_size;
1347
1348         stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format,
1349             &lockeddata_src);
1350         if (stat != Ok) return stat;
1351
1352         stat = GdipCreateBitmapFromScan0(lockeddata_src.Width, lockeddata_src.Height,
1353             0, lockeddata_src.PixelFormat, NULL, (GpBitmap**)cloneImage);
1354         if (stat == Ok)
1355         {
1356             stat = GdipBitmapLockBits((GpBitmap*)*cloneImage, NULL, ImageLockModeWrite,
1357                 lockeddata_src.PixelFormat, &lockeddata_dst);
1358
1359             if (stat == Ok)
1360             {
1361                 /* copy the image data */
1362                 row_size = (lockeddata_src.Width * PIXELFORMATBPP(lockeddata_src.PixelFormat) +7)/8;
1363                 for (i=0; i<lockeddata_src.Height; i++)
1364                     memcpy((BYTE*)lockeddata_dst.Scan0+lockeddata_dst.Stride*i,
1365                            (BYTE*)lockeddata_src.Scan0+lockeddata_src.Stride*i,
1366                            row_size);
1367
1368                 GdipBitmapUnlockBits((GpBitmap*)*cloneImage, &lockeddata_dst);
1369             }
1370
1371             if (stat != Ok)
1372                 GdipDisposeImage(*cloneImage);
1373         }
1374
1375         GdipBitmapUnlockBits(bitmap, &lockeddata_src);
1376
1377         if (stat != Ok)
1378         {
1379             *cloneImage = NULL;
1380         }
1381         else memcpy(&(*cloneImage)->format, &image->format, sizeof(GUID));
1382
1383         return stat;
1384     }
1385     else if (image->type == ImageTypeMetafile && ((GpMetafile*)image)->hemf)
1386     {
1387         GpMetafile *result, *metafile;
1388
1389         metafile = (GpMetafile*)image;
1390
1391         result = GdipAlloc(sizeof(*result));
1392         if (!result)
1393             return OutOfMemory;
1394
1395         result->image.type = ImageTypeMetafile;
1396         result->image.format = image->format;
1397         result->image.flags = image->flags;
1398         result->image.frame_count = 1;
1399         result->image.xres = image->xres;
1400         result->image.yres = image->yres;
1401         result->bounds = metafile->bounds;
1402         result->unit = metafile->unit;
1403         result->metafile_type = metafile->metafile_type;
1404         result->hemf = CopyEnhMetaFileW(metafile->hemf, NULL);
1405
1406         if (!result->hemf)
1407         {
1408             GdipFree(result);
1409             return OutOfMemory;
1410         }
1411
1412         *cloneImage = &result->image;
1413         return Ok;
1414     }
1415     else
1416     {
1417         WARN("GpImage with no image data (metafile in wrong state?)\n");
1418         return InvalidParameter;
1419     }
1420 }
1421
1422 GpStatus WINGDIPAPI GdipCreateBitmapFromFile(GDIPCONST WCHAR* filename,
1423     GpBitmap **bitmap)
1424 {
1425     GpStatus stat;
1426     IStream *stream;
1427
1428     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
1429
1430     if(!filename || !bitmap)
1431         return InvalidParameter;
1432
1433     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
1434
1435     if(stat != Ok)
1436         return stat;
1437
1438     stat = GdipCreateBitmapFromStream(stream, bitmap);
1439
1440     IStream_Release(stream);
1441
1442     return stat;
1443 }
1444
1445 GpStatus WINGDIPAPI GdipCreateBitmapFromGdiDib(GDIPCONST BITMAPINFO* info,
1446                                                VOID *bits, GpBitmap **bitmap)
1447 {
1448     DWORD height, stride;
1449     PixelFormat format;
1450
1451     FIXME("(%p, %p, %p) - partially implemented\n", info, bits, bitmap);
1452
1453     if (!info || !bits || !bitmap)
1454         return InvalidParameter;
1455
1456     height = abs(info->bmiHeader.biHeight);
1457     stride = ((info->bmiHeader.biWidth * info->bmiHeader.biBitCount + 31) >> 3) & ~3;
1458
1459     if(info->bmiHeader.biHeight > 0) /* bottom-up */
1460     {
1461         bits = (BYTE*)bits + (height - 1) * stride;
1462         stride = -stride;
1463     }
1464
1465     switch(info->bmiHeader.biBitCount) {
1466     case 1:
1467         format = PixelFormat1bppIndexed;
1468         break;
1469     case 4:
1470         format = PixelFormat4bppIndexed;
1471         break;
1472     case 8:
1473         format = PixelFormat8bppIndexed;
1474         break;
1475     case 16:
1476         format = PixelFormat16bppRGB555;
1477         break;
1478     case 24:
1479         format = PixelFormat24bppRGB;
1480         break;
1481     case 32:
1482         format = PixelFormat32bppRGB;
1483         break;
1484     default:
1485         FIXME("don't know how to handle %d bpp\n", info->bmiHeader.biBitCount);
1486         *bitmap = NULL;
1487         return InvalidParameter;
1488     }
1489
1490     return GdipCreateBitmapFromScan0(info->bmiHeader.biWidth, height, stride, format,
1491                                      bits, bitmap);
1492
1493 }
1494
1495 /* FIXME: no icm */
1496 GpStatus WINGDIPAPI GdipCreateBitmapFromFileICM(GDIPCONST WCHAR* filename,
1497     GpBitmap **bitmap)
1498 {
1499     TRACE("(%s) %p\n", debugstr_w(filename), bitmap);
1500
1501     return GdipCreateBitmapFromFile(filename, bitmap);
1502 }
1503
1504 GpStatus WINGDIPAPI GdipCreateBitmapFromResource(HINSTANCE hInstance,
1505     GDIPCONST WCHAR* lpBitmapName, GpBitmap** bitmap)
1506 {
1507     HBITMAP hbm;
1508     GpStatus stat = InvalidParameter;
1509
1510     TRACE("%p (%s) %p\n", hInstance, debugstr_w(lpBitmapName), bitmap);
1511
1512     if(!lpBitmapName || !bitmap)
1513         return InvalidParameter;
1514
1515     /* load DIB */
1516     hbm = LoadImageW(hInstance, lpBitmapName, IMAGE_BITMAP, 0, 0,
1517                      LR_CREATEDIBSECTION);
1518
1519     if(hbm){
1520         stat = GdipCreateBitmapFromHBITMAP(hbm, NULL, bitmap);
1521         DeleteObject(hbm);
1522     }
1523
1524     return stat;
1525 }
1526
1527 GpStatus WINGDIPAPI GdipCreateHBITMAPFromBitmap(GpBitmap* bitmap,
1528     HBITMAP* hbmReturn, ARGB background)
1529 {
1530     GpStatus stat;
1531     HBITMAP result;
1532     UINT width, height;
1533     BITMAPINFOHEADER bih;
1534     LPBYTE bits;
1535     BitmapData lockeddata;
1536     TRACE("(%p,%p,%x)\n", bitmap, hbmReturn, background);
1537
1538     if (!bitmap || !hbmReturn) return InvalidParameter;
1539
1540     GdipGetImageWidth((GpImage*)bitmap, &width);
1541     GdipGetImageHeight((GpImage*)bitmap, &height);
1542
1543     bih.biSize = sizeof(bih);
1544     bih.biWidth = width;
1545     bih.biHeight = height;
1546     bih.biPlanes = 1;
1547     bih.biBitCount = 32;
1548     bih.biCompression = BI_RGB;
1549     bih.biSizeImage = 0;
1550     bih.biXPelsPerMeter = 0;
1551     bih.biYPelsPerMeter = 0;
1552     bih.biClrUsed = 0;
1553     bih.biClrImportant = 0;
1554
1555     result = CreateDIBSection(0, (BITMAPINFO*)&bih, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
1556
1557     if (result)
1558     {
1559         lockeddata.Stride = -width * 4;
1560         lockeddata.Scan0 = bits + (width * 4 * (height - 1));
1561
1562         stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead|ImageLockModeUserInputBuf,
1563             PixelFormat32bppPARGB, &lockeddata);
1564
1565         if (stat == Ok)
1566             stat = GdipBitmapUnlockBits(bitmap, &lockeddata);
1567     }
1568     else
1569         stat = GenericError;
1570
1571     if (stat != Ok && result)
1572     {
1573         DeleteObject(result);
1574         result = NULL;
1575     }
1576
1577     *hbmReturn = result;
1578
1579     return stat;
1580 }
1581
1582 GpStatus WINGDIPAPI GdipConvertToEmfPlus(const GpGraphics* ref,
1583     GpMetafile* metafile, BOOL* succ, EmfType emfType,
1584     const WCHAR* description, GpMetafile** out_metafile)
1585 {
1586     static int calls;
1587
1588     TRACE("(%p,%p,%p,%u,%s,%p)\n", ref, metafile, succ, emfType,
1589         debugstr_w(description), out_metafile);
1590
1591     if(!ref || !metafile || !out_metafile)
1592         return InvalidParameter;
1593
1594     *succ = FALSE;
1595     *out_metafile = NULL;
1596
1597     if(!(calls++))
1598         FIXME("not implemented\n");
1599
1600     return NotImplemented;
1601 }
1602
1603 /* FIXME: this should create a bitmap in the given size with the attributes
1604  * (resolution etc.) of the graphics object */
1605 GpStatus WINGDIPAPI GdipCreateBitmapFromGraphics(INT width, INT height,
1606     GpGraphics* target, GpBitmap** bitmap)
1607 {
1608     static int calls;
1609     GpStatus ret;
1610
1611     TRACE("(%d, %d, %p, %p)\n", width, height, target, bitmap);
1612
1613     if(!target || !bitmap)
1614         return InvalidParameter;
1615
1616     if(!(calls++))
1617         FIXME("hacked stub\n");
1618
1619     ret = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat24bppRGB,
1620                                     NULL, bitmap);
1621
1622     return ret;
1623 }
1624
1625 GpStatus WINGDIPAPI GdipCreateBitmapFromHICON(HICON hicon, GpBitmap** bitmap)
1626 {
1627     GpStatus stat;
1628     ICONINFO iinfo;
1629     BITMAP bm;
1630     int ret;
1631     UINT width, height;
1632     GpRect rect;
1633     BitmapData lockeddata;
1634     HDC screendc;
1635     BOOL has_alpha;
1636     int x, y;
1637     BYTE *bits;
1638     BITMAPINFOHEADER bih;
1639     DWORD *src;
1640     BYTE *dst_row;
1641     DWORD *dst;
1642
1643     TRACE("%p, %p\n", hicon, bitmap);
1644
1645     if(!bitmap || !GetIconInfo(hicon, &iinfo))
1646         return InvalidParameter;
1647
1648     /* get the size of the icon */
1649     ret = GetObjectA(iinfo.hbmColor ? iinfo.hbmColor : iinfo.hbmMask, sizeof(bm), &bm);
1650     if (ret == 0) {
1651         DeleteObject(iinfo.hbmColor);
1652         DeleteObject(iinfo.hbmMask);
1653         return GenericError;
1654     }
1655
1656     width = bm.bmWidth;
1657
1658     if (iinfo.hbmColor)
1659         height = abs(bm.bmHeight);
1660     else /* combined bitmap + mask */
1661         height = abs(bm.bmHeight) / 2;
1662
1663     bits = HeapAlloc(GetProcessHeap(), 0, 4*width*height);
1664     if (!bits) {
1665         DeleteObject(iinfo.hbmColor);
1666         DeleteObject(iinfo.hbmMask);
1667         return OutOfMemory;
1668     }
1669
1670     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppARGB, NULL, bitmap);
1671     if (stat != Ok) {
1672         DeleteObject(iinfo.hbmColor);
1673         DeleteObject(iinfo.hbmMask);
1674         HeapFree(GetProcessHeap(), 0, bits);
1675         return stat;
1676     }
1677
1678     rect.X = 0;
1679     rect.Y = 0;
1680     rect.Width = width;
1681     rect.Height = height;
1682
1683     stat = GdipBitmapLockBits(*bitmap, &rect, ImageLockModeWrite, PixelFormat32bppARGB, &lockeddata);
1684     if (stat != Ok) {
1685         DeleteObject(iinfo.hbmColor);
1686         DeleteObject(iinfo.hbmMask);
1687         HeapFree(GetProcessHeap(), 0, bits);
1688         GdipDisposeImage((GpImage*)*bitmap);
1689         return stat;
1690     }
1691
1692     bih.biSize = sizeof(bih);
1693     bih.biWidth = width;
1694     bih.biHeight = -height;
1695     bih.biPlanes = 1;
1696     bih.biBitCount = 32;
1697     bih.biCompression = BI_RGB;
1698     bih.biSizeImage = 0;
1699     bih.biXPelsPerMeter = 0;
1700     bih.biYPelsPerMeter = 0;
1701     bih.biClrUsed = 0;
1702     bih.biClrImportant = 0;
1703
1704     screendc = GetDC(0);
1705     if (iinfo.hbmColor)
1706     {
1707         GetDIBits(screendc, iinfo.hbmColor, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1708
1709         if (bm.bmBitsPixel == 32)
1710         {
1711             has_alpha = FALSE;
1712
1713             /* If any pixel has a non-zero alpha, ignore hbmMask */
1714             src = (DWORD*)bits;
1715             for (x=0; x<width && !has_alpha; x++)
1716                 for (y=0; y<height && !has_alpha; y++)
1717                     if ((*src++ & 0xff000000) != 0)
1718                         has_alpha = TRUE;
1719         }
1720         else has_alpha = FALSE;
1721     }
1722     else
1723     {
1724         GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1725         has_alpha = FALSE;
1726     }
1727
1728     /* copy the image data to the Bitmap */
1729     src = (DWORD*)bits;
1730     dst_row = lockeddata.Scan0;
1731     for (y=0; y<height; y++)
1732     {
1733         memcpy(dst_row, src, width*4);
1734         src += width;
1735         dst_row += lockeddata.Stride;
1736     }
1737
1738     if (!has_alpha)
1739     {
1740         if (iinfo.hbmMask)
1741         {
1742             /* read alpha data from the mask */
1743             if (iinfo.hbmColor)
1744                 GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1745             else
1746                 GetDIBits(screendc, iinfo.hbmMask, height, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1747
1748             src = (DWORD*)bits;
1749             dst_row = lockeddata.Scan0;
1750             for (y=0; y<height; y++)
1751             {
1752                 dst = (DWORD*)dst_row;
1753                 for (x=0; x<height; x++)
1754                 {
1755                     DWORD src_value = *src++;
1756                     if (src_value)
1757                         *dst++ = 0;
1758                     else
1759                         *dst++ |= 0xff000000;
1760                 }
1761                 dst_row += lockeddata.Stride;
1762             }
1763         }
1764         else
1765         {
1766             /* set constant alpha of 255 */
1767             dst_row = bits;
1768             for (y=0; y<height; y++)
1769             {
1770                 dst = (DWORD*)dst_row;
1771                 for (x=0; x<height; x++)
1772                     *dst++ |= 0xff000000;
1773                 dst_row += lockeddata.Stride;
1774             }
1775         }
1776     }
1777
1778     ReleaseDC(0, screendc);
1779
1780     DeleteObject(iinfo.hbmColor);
1781     DeleteObject(iinfo.hbmMask);
1782
1783     GdipBitmapUnlockBits(*bitmap, &lockeddata);
1784
1785     HeapFree(GetProcessHeap(), 0, bits);
1786
1787     return Ok;
1788 }
1789
1790 static void generate_halftone_palette(ARGB *entries, UINT count)
1791 {
1792     static const BYTE halftone_values[6]={0x00,0x33,0x66,0x99,0xcc,0xff};
1793     UINT i;
1794
1795     for (i=0; i<8 && i<count; i++)
1796     {
1797         entries[i] = 0xff000000;
1798         if (i&1) entries[i] |= 0x800000;
1799         if (i&2) entries[i] |= 0x8000;
1800         if (i&4) entries[i] |= 0x80;
1801     }
1802
1803     if (8 < count)
1804         entries[i] = 0xffc0c0c0;
1805
1806     for (i=9; i<16 && i<count; i++)
1807     {
1808         entries[i] = 0xff000000;
1809         if (i&1) entries[i] |= 0xff0000;
1810         if (i&2) entries[i] |= 0xff00;
1811         if (i&4) entries[i] |= 0xff;
1812     }
1813
1814     for (i=16; i<40 && i<count; i++)
1815     {
1816         entries[i] = 0;
1817     }
1818
1819     for (i=40; i<256 && i<count; i++)
1820     {
1821         entries[i] = 0xff000000;
1822         entries[i] |= halftone_values[(i-40)%6];
1823         entries[i] |= halftone_values[((i-40)/6)%6] << 8;
1824         entries[i] |= halftone_values[((i-40)/36)%6] << 16;
1825     }
1826 }
1827
1828 static GpStatus get_screen_resolution(REAL *xres, REAL *yres)
1829 {
1830     HDC screendc = GetDC(0);
1831
1832     if (!screendc) return GenericError;
1833
1834     *xres = (REAL)GetDeviceCaps(screendc, LOGPIXELSX);
1835     *yres = (REAL)GetDeviceCaps(screendc, LOGPIXELSY);
1836
1837     ReleaseDC(0, screendc);
1838
1839     return Ok;
1840 }
1841
1842 GpStatus WINGDIPAPI GdipCreateBitmapFromScan0(INT width, INT height, INT stride,
1843     PixelFormat format, BYTE* scan0, GpBitmap** bitmap)
1844 {
1845     BITMAPINFO* pbmi;
1846     HBITMAP hbitmap=NULL;
1847     INT row_size, dib_stride;
1848     BYTE *bits=NULL, *own_bits=NULL;
1849     REAL xres, yres;
1850     GpStatus stat;
1851
1852     TRACE("%d %d %d 0x%x %p %p\n", width, height, stride, format, scan0, bitmap);
1853
1854     if (!bitmap) return InvalidParameter;
1855
1856     if(width <= 0 || height <= 0 || (scan0 && (stride % 4))){
1857         *bitmap = NULL;
1858         return InvalidParameter;
1859     }
1860
1861     if(scan0 && !stride)
1862         return InvalidParameter;
1863
1864     stat = get_screen_resolution(&xres, &yres);
1865     if (stat != Ok) return stat;
1866
1867     row_size = (width * PIXELFORMATBPP(format)+7) / 8;
1868     dib_stride = (row_size + 3) & ~3;
1869
1870     if(stride == 0)
1871         stride = dib_stride;
1872
1873     if (format & PixelFormatGDI && !(format & (PixelFormatAlpha|PixelFormatIndexed)) && !scan0)
1874     {
1875         pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
1876         if (!pbmi)
1877             return OutOfMemory;
1878
1879         pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1880         pbmi->bmiHeader.biWidth = width;
1881         pbmi->bmiHeader.biHeight = -height;
1882         pbmi->bmiHeader.biPlanes = 1;
1883         /* FIXME: use the rest of the data from format */
1884         pbmi->bmiHeader.biBitCount = PIXELFORMATBPP(format);
1885         pbmi->bmiHeader.biCompression = BI_RGB;
1886         pbmi->bmiHeader.biSizeImage = 0;
1887         pbmi->bmiHeader.biXPelsPerMeter = 0;
1888         pbmi->bmiHeader.biYPelsPerMeter = 0;
1889         pbmi->bmiHeader.biClrUsed = 0;
1890         pbmi->bmiHeader.biClrImportant = 0;
1891
1892         hbitmap = CreateDIBSection(0, pbmi, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
1893
1894         GdipFree(pbmi);
1895
1896         if (!hbitmap) return GenericError;
1897
1898         stride = dib_stride;
1899     }
1900     else
1901     {
1902         /* Not a GDI format; don't try to make an HBITMAP. */
1903         if (scan0)
1904             bits = scan0;
1905         else
1906         {
1907             INT size = abs(stride) * height;
1908
1909             own_bits = bits = GdipAlloc(size);
1910             if (!own_bits) return OutOfMemory;
1911
1912             if (stride < 0)
1913                 bits += stride * (1 - height);
1914         }
1915     }
1916
1917     *bitmap = GdipAlloc(sizeof(GpBitmap));
1918     if(!*bitmap)
1919     {
1920         DeleteObject(hbitmap);
1921         GdipFree(own_bits);
1922         return OutOfMemory;
1923     }
1924
1925     (*bitmap)->image.type = ImageTypeBitmap;
1926     memcpy(&(*bitmap)->image.format, &ImageFormatMemoryBMP, sizeof(GUID));
1927     (*bitmap)->image.flags = ImageFlagsNone;
1928     (*bitmap)->image.frame_count = 1;
1929     (*bitmap)->image.current_frame = 0;
1930     (*bitmap)->image.palette = NULL;
1931     (*bitmap)->image.xres = xres;
1932     (*bitmap)->image.yres = yres;
1933     (*bitmap)->width = width;
1934     (*bitmap)->height = height;
1935     (*bitmap)->format = format;
1936     (*bitmap)->image.picture = NULL;
1937     (*bitmap)->image.stream = NULL;
1938     (*bitmap)->hbitmap = hbitmap;
1939     (*bitmap)->hdc = NULL;
1940     (*bitmap)->bits = bits;
1941     (*bitmap)->stride = stride;
1942     (*bitmap)->own_bits = own_bits;
1943     (*bitmap)->metadata_reader = NULL;
1944     (*bitmap)->prop_count = 0;
1945     (*bitmap)->prop_item = NULL;
1946
1947     /* set format-related flags */
1948     if (format & (PixelFormatAlpha|PixelFormatPAlpha|PixelFormatIndexed))
1949         (*bitmap)->image.flags |= ImageFlagsHasAlpha;
1950
1951     if (format == PixelFormat1bppIndexed ||
1952         format == PixelFormat4bppIndexed ||
1953         format == PixelFormat8bppIndexed)
1954     {
1955         (*bitmap)->image.palette = GdipAlloc(sizeof(UINT) * 2 + sizeof(ARGB) * (1 << PIXELFORMATBPP(format)));
1956
1957         if (!(*bitmap)->image.palette)
1958         {
1959             GdipDisposeImage(&(*bitmap)->image);
1960             *bitmap = NULL;
1961             return OutOfMemory;
1962         }
1963
1964         (*bitmap)->image.palette->Count = 1 << PIXELFORMATBPP(format);
1965
1966         if (format == PixelFormat1bppIndexed)
1967         {
1968             (*bitmap)->image.palette->Flags = PaletteFlagsGrayScale;
1969             (*bitmap)->image.palette->Entries[0] = 0xff000000;
1970             (*bitmap)->image.palette->Entries[1] = 0xffffffff;
1971         }
1972         else
1973         {
1974             if (format == PixelFormat8bppIndexed)
1975                 (*bitmap)->image.palette->Flags = PaletteFlagsHalftone;
1976
1977             generate_halftone_palette((*bitmap)->image.palette->Entries,
1978                 (*bitmap)->image.palette->Count);
1979         }
1980     }
1981
1982     TRACE("<-- %p\n", *bitmap);
1983
1984     return Ok;
1985 }
1986
1987 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
1988     GpBitmap **bitmap)
1989 {
1990     GpStatus stat;
1991
1992     TRACE("%p %p\n", stream, bitmap);
1993
1994     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
1995
1996     if(stat != Ok)
1997         return stat;
1998
1999     if((*bitmap)->image.type != ImageTypeBitmap){
2000         GdipDisposeImage(&(*bitmap)->image);
2001         *bitmap = NULL;
2002         return GenericError; /* FIXME: what error to return? */
2003     }
2004
2005     return Ok;
2006 }
2007
2008 /* FIXME: no icm */
2009 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
2010     GpBitmap **bitmap)
2011 {
2012     TRACE("%p %p\n", stream, bitmap);
2013
2014     return GdipCreateBitmapFromStream(stream, bitmap);
2015 }
2016
2017 GpStatus WINGDIPAPI GdipCreateCachedBitmap(GpBitmap *bitmap, GpGraphics *graphics,
2018     GpCachedBitmap **cachedbmp)
2019 {
2020     GpStatus stat;
2021
2022     TRACE("%p %p %p\n", bitmap, graphics, cachedbmp);
2023
2024     if(!bitmap || !graphics || !cachedbmp)
2025         return InvalidParameter;
2026
2027     *cachedbmp = GdipAlloc(sizeof(GpCachedBitmap));
2028     if(!*cachedbmp)
2029         return OutOfMemory;
2030
2031     stat = GdipCloneImage(&(bitmap->image), &(*cachedbmp)->image);
2032     if(stat != Ok){
2033         GdipFree(*cachedbmp);
2034         return stat;
2035     }
2036
2037     return Ok;
2038 }
2039
2040 GpStatus WINGDIPAPI GdipCreateHICONFromBitmap(GpBitmap *bitmap, HICON *hicon)
2041 {
2042     GpStatus stat;
2043     BitmapData lockeddata;
2044     ULONG andstride, xorstride, bitssize;
2045     LPBYTE andbits, xorbits, androw, xorrow, srcrow;
2046     UINT x, y;
2047
2048     TRACE("(%p, %p)\n", bitmap, hicon);
2049
2050     if (!bitmap || !hicon)
2051         return InvalidParameter;
2052
2053     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead,
2054         PixelFormat32bppPARGB, &lockeddata);
2055     if (stat == Ok)
2056     {
2057         andstride = ((lockeddata.Width+31)/32)*4;
2058         xorstride = lockeddata.Width*4;
2059         bitssize = (andstride + xorstride) * lockeddata.Height;
2060
2061         andbits = GdipAlloc(bitssize);
2062
2063         if (andbits)
2064         {
2065             xorbits = andbits + andstride * lockeddata.Height;
2066
2067             for (y=0; y<lockeddata.Height; y++)
2068             {
2069                 srcrow = ((LPBYTE)lockeddata.Scan0) + lockeddata.Stride * y;
2070
2071                 androw = andbits + andstride * y;
2072                 for (x=0; x<lockeddata.Width; x++)
2073                     if (srcrow[3+4*x] >= 128)
2074                         androw[x/8] |= 1 << (7-x%8);
2075
2076                 xorrow = xorbits + xorstride * y;
2077                 memcpy(xorrow, srcrow, xorstride);
2078             }
2079
2080             *hicon = CreateIcon(NULL, lockeddata.Width, lockeddata.Height, 1, 32,
2081                 andbits, xorbits);
2082
2083             GdipFree(andbits);
2084         }
2085         else
2086             stat = OutOfMemory;
2087
2088         GdipBitmapUnlockBits(bitmap, &lockeddata);
2089     }
2090
2091     return stat;
2092 }
2093
2094 GpStatus WINGDIPAPI GdipDeleteCachedBitmap(GpCachedBitmap *cachedbmp)
2095 {
2096     TRACE("%p\n", cachedbmp);
2097
2098     if(!cachedbmp)
2099         return InvalidParameter;
2100
2101     GdipDisposeImage(cachedbmp->image);
2102     GdipFree(cachedbmp);
2103
2104     return Ok;
2105 }
2106
2107 GpStatus WINGDIPAPI GdipDrawCachedBitmap(GpGraphics *graphics,
2108     GpCachedBitmap *cachedbmp, INT x, INT y)
2109 {
2110     TRACE("%p %p %d %d\n", graphics, cachedbmp, x, y);
2111
2112     if(!graphics || !cachedbmp)
2113         return InvalidParameter;
2114
2115     return GdipDrawImage(graphics, cachedbmp->image, (REAL)x, (REAL)y);
2116 }
2117
2118 GpStatus WINGDIPAPI GdipEmfToWmfBits(HENHMETAFILE hemf, UINT cbData16,
2119     LPBYTE pData16, INT iMapMode, INT eFlags)
2120 {
2121     FIXME("(%p, %d, %p, %d, %d): stub\n", hemf, cbData16, pData16, iMapMode, eFlags);
2122     return NotImplemented;
2123 }
2124
2125 /* Internal utility function: Replace the image data of dst with that of src,
2126  * and free src. */
2127 static void move_bitmap(GpBitmap *dst, GpBitmap *src, BOOL clobber_palette)
2128 {
2129     assert(src->image.type == ImageTypeBitmap);
2130     assert(dst->image.type == ImageTypeBitmap);
2131
2132     GdipFree(dst->bitmapbits);
2133     GdipFree(dst->own_bits);
2134     DeleteDC(dst->hdc);
2135     DeleteObject(dst->hbitmap);
2136
2137     if (clobber_palette)
2138     {
2139         GdipFree(dst->image.palette);
2140         dst->image.palette = src->image.palette;
2141     }
2142     else
2143         GdipFree(src->image.palette);
2144
2145     dst->image.xres = src->image.xres;
2146     dst->image.yres = src->image.yres;
2147     dst->width = src->width;
2148     dst->height = src->height;
2149     dst->format = src->format;
2150     dst->hbitmap = src->hbitmap;
2151     dst->hdc = src->hdc;
2152     dst->bits = src->bits;
2153     dst->stride = src->stride;
2154     dst->own_bits = src->own_bits;
2155     if (dst->metadata_reader)
2156         IWICMetadataReader_Release(dst->metadata_reader);
2157     dst->metadata_reader = src->metadata_reader;
2158     GdipFree(dst->prop_item);
2159     dst->prop_item = src->prop_item;
2160     dst->prop_count = src->prop_count;
2161     if (dst->image.stream)
2162         IStream_Release(dst->image.stream);
2163     dst->image.stream = src->image.stream;
2164     dst->image.frame_count = src->image.frame_count;
2165     dst->image.current_frame = src->image.current_frame;
2166     dst->image.format = src->image.format;
2167
2168     src->image.type = ~0;
2169     GdipFree(src);
2170 }
2171
2172 static GpStatus free_image_data(GpImage *image)
2173 {
2174     if(!image)
2175         return InvalidParameter;
2176
2177     if (image->type == ImageTypeBitmap)
2178     {
2179         GdipFree(((GpBitmap*)image)->bitmapbits);
2180         GdipFree(((GpBitmap*)image)->own_bits);
2181         DeleteDC(((GpBitmap*)image)->hdc);
2182         DeleteObject(((GpBitmap*)image)->hbitmap);
2183         if (((GpBitmap*)image)->metadata_reader)
2184             IWICMetadataReader_Release(((GpBitmap*)image)->metadata_reader);
2185         GdipFree(((GpBitmap*)image)->prop_item);
2186     }
2187     else if (image->type == ImageTypeMetafile)
2188     {
2189         GpMetafile *metafile = (GpMetafile*)image;
2190         GdipFree(metafile->comment_data);
2191         DeleteEnhMetaFile(CloseEnhMetaFile(metafile->record_dc));
2192         if (!metafile->preserve_hemf)
2193             DeleteEnhMetaFile(metafile->hemf);
2194         if (metafile->record_graphics)
2195         {
2196             WARN("metafile closed while recording\n");
2197             /* not sure what to do here; for now just prevent the graphics from functioning or using this object */
2198             metafile->record_graphics->image = NULL;
2199             metafile->record_graphics->busy = TRUE;
2200         }
2201     }
2202     else
2203     {
2204         WARN("invalid image: %p\n", image);
2205         return ObjectBusy;
2206     }
2207     if (image->picture)
2208         IPicture_Release(image->picture);
2209     if (image->stream)
2210         IStream_Release(image->stream);
2211     GdipFree(image->palette);
2212
2213     return Ok;
2214 }
2215
2216 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
2217 {
2218     GpStatus status;
2219
2220     TRACE("%p\n", image);
2221
2222     status = free_image_data(image);
2223     if (status != Ok) return status;
2224     image->type = ~0;
2225     GdipFree(image);
2226
2227     return Ok;
2228 }
2229
2230 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
2231 {
2232     static int calls;
2233
2234     TRACE("(%p,%p)\n", image, item);
2235
2236     if(!image || !item)
2237         return InvalidParameter;
2238
2239     if (!(calls++))
2240         FIXME("not implemented\n");
2241
2242     return NotImplemented;
2243 }
2244
2245 GpStatus WINGDIPAPI GdipGetImageItemData(GpImage *image, ImageItemData *item)
2246 {
2247     static int calls;
2248
2249     TRACE("(%p,%p)\n", image, item);
2250
2251     if (!(calls++))
2252         FIXME("not implemented\n");
2253
2254     return NotImplemented;
2255 }
2256
2257 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
2258     GpUnit *srcUnit)
2259 {
2260     TRACE("%p %p %p\n", image, srcRect, srcUnit);
2261
2262     if(!image || !srcRect || !srcUnit)
2263         return InvalidParameter;
2264     if(image->type == ImageTypeMetafile){
2265         *srcRect = ((GpMetafile*)image)->bounds;
2266         *srcUnit = ((GpMetafile*)image)->unit;
2267     }
2268     else if(image->type == ImageTypeBitmap){
2269         srcRect->X = srcRect->Y = 0.0;
2270         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
2271         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
2272         *srcUnit = UnitPixel;
2273     }
2274     else{
2275         srcRect->X = srcRect->Y = 0.0;
2276         srcRect->Width = ipicture_pixel_width(image->picture);
2277         srcRect->Height = ipicture_pixel_height(image->picture);
2278         *srcUnit = UnitPixel;
2279     }
2280
2281     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
2282           srcRect->Width, srcRect->Height, *srcUnit);
2283
2284     return Ok;
2285 }
2286
2287 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
2288     REAL *height)
2289 {
2290     TRACE("%p %p %p\n", image, width, height);
2291
2292     if(!image || !height || !width)
2293         return InvalidParameter;
2294
2295     if(image->type == ImageTypeMetafile){
2296         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2297         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2298     }
2299     else if(image->type == ImageTypeBitmap){
2300         *height = ((GpBitmap*)image)->height;
2301         *width = ((GpBitmap*)image)->width;
2302     }
2303     else{
2304         *height = ipicture_pixel_height(image->picture);
2305         *width = ipicture_pixel_width(image->picture);
2306     }
2307
2308     TRACE("returning (%f, %f)\n", *height, *width);
2309     return Ok;
2310 }
2311
2312 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
2313     GpGraphics **graphics)
2314 {
2315     HDC hdc;
2316     GpStatus stat;
2317
2318     TRACE("%p %p\n", image, graphics);
2319
2320     if(!image || !graphics)
2321         return InvalidParameter;
2322
2323     if (image->type == ImageTypeBitmap && ((GpBitmap*)image)->hbitmap)
2324     {
2325         hdc = ((GpBitmap*)image)->hdc;
2326
2327         if(!hdc){
2328             hdc = CreateCompatibleDC(0);
2329             SelectObject(hdc, ((GpBitmap*)image)->hbitmap);
2330             ((GpBitmap*)image)->hdc = hdc;
2331         }
2332
2333         stat = GdipCreateFromHDC(hdc, graphics);
2334
2335         if (stat == Ok)
2336         {
2337             (*graphics)->image = image;
2338             (*graphics)->xres = image->xres;
2339             (*graphics)->yres = image->yres;
2340         }
2341     }
2342     else if (image->type == ImageTypeMetafile)
2343         stat = METAFILE_GetGraphicsContext((GpMetafile*)image, graphics);
2344     else
2345         stat = graphics_from_image(image, graphics);
2346
2347     return stat;
2348 }
2349
2350 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
2351 {
2352     TRACE("%p %p\n", image, height);
2353
2354     if(!image || !height)
2355         return InvalidParameter;
2356
2357     if(image->type == ImageTypeMetafile)
2358         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2359     else if(image->type == ImageTypeBitmap)
2360         *height = ((GpBitmap*)image)->height;
2361     else
2362         *height = ipicture_pixel_height(image->picture);
2363
2364     TRACE("returning %d\n", *height);
2365
2366     return Ok;
2367 }
2368
2369 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
2370 {
2371     if(!image || !res)
2372         return InvalidParameter;
2373
2374     *res = image->xres;
2375
2376     TRACE("(%p) <-- %0.2f\n", image, *res);
2377
2378     return Ok;
2379 }
2380
2381 GpStatus WINGDIPAPI GdipGetImagePaletteSize(GpImage *image, INT *size)
2382 {
2383     TRACE("%p %p\n", image, size);
2384
2385     if(!image || !size)
2386         return InvalidParameter;
2387
2388     if (!image->palette || image->palette->Count == 0)
2389         *size = sizeof(ColorPalette);
2390     else
2391         *size = sizeof(UINT)*2 + sizeof(ARGB)*image->palette->Count;
2392
2393     TRACE("<-- %u\n", *size);
2394
2395     return Ok;
2396 }
2397
2398 /* FIXME: test this function for non-bitmap types */
2399 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
2400 {
2401     TRACE("%p %p\n", image, format);
2402
2403     if(!image || !format)
2404         return InvalidParameter;
2405
2406     if(image->type != ImageTypeBitmap)
2407         *format = PixelFormat24bppRGB;
2408     else
2409         *format = ((GpBitmap*) image)->format;
2410
2411     return Ok;
2412 }
2413
2414 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
2415 {
2416     TRACE("(%p, %p)\n", image, format);
2417
2418     if(!image || !format)
2419         return InvalidParameter;
2420
2421     memcpy(format, &image->format, sizeof(GUID));
2422
2423     return Ok;
2424 }
2425
2426 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
2427 {
2428     TRACE("%p %p\n", image, type);
2429
2430     if(!image || !type)
2431         return InvalidParameter;
2432
2433     *type = image->type;
2434
2435     return Ok;
2436 }
2437
2438 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
2439 {
2440     if(!image || !res)
2441         return InvalidParameter;
2442
2443     *res = image->yres;
2444
2445     TRACE("(%p) <-- %0.2f\n", image, *res);
2446
2447     return Ok;
2448 }
2449
2450 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
2451 {
2452     TRACE("%p %p\n", image, width);
2453
2454     if(!image || !width)
2455         return InvalidParameter;
2456
2457     if(image->type == ImageTypeMetafile)
2458         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2459     else if(image->type == ImageTypeBitmap)
2460         *width = ((GpBitmap*)image)->width;
2461     else
2462         *width = ipicture_pixel_width(image->picture);
2463
2464     TRACE("returning %d\n", *width);
2465
2466     return Ok;
2467 }
2468
2469 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
2470     MetafileHeader * header)
2471 {
2472     static int calls;
2473
2474     TRACE("(%p, %p)\n", metafile, header);
2475
2476     if(!metafile || !header)
2477         return InvalidParameter;
2478
2479     if(!(calls++))
2480         FIXME("not implemented\n");
2481
2482     memset(header, 0, sizeof(MetafileHeader));
2483
2484     return Ok;
2485 }
2486
2487 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromEmf(HENHMETAFILE hEmf,
2488     MetafileHeader *header)
2489 {
2490     static int calls;
2491
2492     if(!hEmf || !header)
2493         return InvalidParameter;
2494
2495     if(!(calls++))
2496         FIXME("not implemented\n");
2497
2498     memset(header, 0, sizeof(MetafileHeader));
2499
2500     return Ok;
2501 }
2502
2503 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromFile(GDIPCONST WCHAR *filename,
2504     MetafileHeader *header)
2505 {
2506     static int calls;
2507
2508     TRACE("(%s,%p)\n", debugstr_w(filename), header);
2509
2510     if(!filename || !header)
2511         return InvalidParameter;
2512
2513     if(!(calls++))
2514         FIXME("not implemented\n");
2515
2516     memset(header, 0, sizeof(MetafileHeader));
2517
2518     return Ok;
2519 }
2520
2521 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromStream(IStream *stream,
2522     MetafileHeader *header)
2523 {
2524     static int calls;
2525
2526     TRACE("(%p,%p)\n", stream, header);
2527
2528     if(!stream || !header)
2529         return InvalidParameter;
2530
2531     if(!(calls++))
2532         FIXME("not implemented\n");
2533
2534     memset(header, 0, sizeof(MetafileHeader));
2535
2536     return Ok;
2537 }
2538
2539 GpStatus WINGDIPAPI GdipGetPropertyCount(GpImage *image, UINT *num)
2540 {
2541     TRACE("(%p, %p)\n", image, num);
2542
2543     if (!image || !num) return InvalidParameter;
2544
2545     *num = 0;
2546
2547     if (image->type == ImageTypeBitmap)
2548     {
2549         if (((GpBitmap *)image)->prop_item)
2550         {
2551             *num = ((GpBitmap *)image)->prop_count;
2552             return Ok;
2553         }
2554
2555         if (((GpBitmap *)image)->metadata_reader)
2556             IWICMetadataReader_GetCount(((GpBitmap *)image)->metadata_reader, num);
2557     }
2558
2559     return Ok;
2560 }
2561
2562 GpStatus WINGDIPAPI GdipGetPropertyIdList(GpImage *image, UINT num, PROPID *list)
2563 {
2564     HRESULT hr;
2565     IWICMetadataReader *reader;
2566     IWICEnumMetadataItem *enumerator;
2567     UINT prop_count, i, items_returned;
2568
2569     TRACE("(%p, %u, %p)\n", image, num, list);
2570
2571     if (!image || !list) return InvalidParameter;
2572
2573     if (image->type != ImageTypeBitmap)
2574     {
2575         FIXME("Not implemented for type %d\n", image->type);
2576         return NotImplemented;
2577     }
2578
2579     if (((GpBitmap *)image)->prop_item)
2580     {
2581         if (num != ((GpBitmap *)image)->prop_count) return InvalidParameter;
2582
2583         for (i = 0; i < num; i++)
2584         {
2585             list[i] = ((GpBitmap *)image)->prop_item[i].id;
2586         }
2587
2588         return Ok;
2589     }
2590
2591     reader = ((GpBitmap *)image)->metadata_reader;
2592     if (!reader)
2593     {
2594         if (num != 0) return InvalidParameter;
2595         return Ok;
2596     }
2597
2598     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2599     if (FAILED(hr)) return hresult_to_status(hr);
2600
2601     if (num != prop_count) return InvalidParameter;
2602
2603     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2604     if (FAILED(hr)) return hresult_to_status(hr);
2605
2606     IWICEnumMetadataItem_Reset(enumerator);
2607
2608     for (i = 0; i < num; i++)
2609     {
2610         PROPVARIANT id;
2611
2612         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, NULL, &items_returned);
2613         if (hr != S_OK) break;
2614
2615         if (id.vt != VT_UI2)
2616         {
2617             FIXME("not supported propvariant type for id: %u\n", id.vt);
2618             list[i] = 0;
2619             continue;
2620         }
2621         list[i] = id.u.uiVal;
2622     }
2623
2624     IWICEnumMetadataItem_Release(enumerator);
2625
2626     return hr == S_OK ? Ok : hresult_to_status(hr);
2627 }
2628
2629 static UINT propvariant_size(PROPVARIANT *value)
2630 {
2631     switch (value->vt & ~VT_VECTOR)
2632     {
2633     case VT_EMPTY:
2634         return 0;
2635     case VT_I1:
2636     case VT_UI1:
2637         if (!(value->vt & VT_VECTOR)) return 1;
2638         return value->u.caub.cElems;
2639     case VT_I2:
2640     case VT_UI2:
2641         if (!(value->vt & VT_VECTOR)) return 2;
2642         return value->u.caui.cElems * 2;
2643     case VT_I4:
2644     case VT_UI4:
2645     case VT_R4:
2646         if (!(value->vt & VT_VECTOR)) return 4;
2647         return value->u.caul.cElems * 4;
2648     case VT_I8:
2649     case VT_UI8:
2650     case VT_R8:
2651         if (!(value->vt & VT_VECTOR)) return 8;
2652         return value->u.cauh.cElems * 8;
2653     case VT_LPSTR:
2654         return value->u.pszVal ? strlen(value->u.pszVal) + 1 : 0;
2655     case VT_BLOB:
2656         return value->u.blob.cbSize;
2657     default:
2658         FIXME("not supported variant type %d\n", value->vt);
2659         return 0;
2660     }
2661 }
2662
2663 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID propid, UINT *size)
2664 {
2665     HRESULT hr;
2666     IWICMetadataReader *reader;
2667     PROPVARIANT id, value;
2668
2669     TRACE("(%p,%#x,%p)\n", image, propid, size);
2670
2671     if (!size || !image) return InvalidParameter;
2672
2673     if (image->type != ImageTypeBitmap)
2674     {
2675         FIXME("Not implemented for type %d\n", image->type);
2676         return NotImplemented;
2677     }
2678
2679     if (((GpBitmap *)image)->prop_item)
2680     {
2681         UINT i;
2682
2683         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2684         {
2685             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2686             {
2687                 *size = sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2688                 return Ok;
2689             }
2690         }
2691
2692         return PropertyNotFound;
2693     }
2694
2695     reader = ((GpBitmap *)image)->metadata_reader;
2696     if (!reader) return PropertyNotFound;
2697
2698     id.vt = VT_UI2;
2699     id.u.uiVal = propid;
2700     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2701     if (FAILED(hr)) return PropertyNotFound;
2702
2703     *size = propvariant_size(&value);
2704     if (*size) *size += sizeof(PropertyItem);
2705     PropVariantClear(&value);
2706
2707     return Ok;
2708 }
2709
2710 #ifndef PropertyTagTypeSByte
2711 #define PropertyTagTypeSByte  6
2712 #define PropertyTagTypeSShort 8
2713 #define PropertyTagTypeFloat  11
2714 #define PropertyTagTypeDouble 12
2715 #endif
2716
2717 static UINT vt_to_itemtype(UINT vt)
2718 {
2719     static const struct
2720     {
2721         UINT vt, type;
2722     } vt2type[] =
2723     {
2724         { VT_I1, PropertyTagTypeSByte },
2725         { VT_UI1, PropertyTagTypeByte },
2726         { VT_I2, PropertyTagTypeSShort },
2727         { VT_UI2, PropertyTagTypeShort },
2728         { VT_I4, PropertyTagTypeSLONG },
2729         { VT_UI4, PropertyTagTypeLong },
2730         { VT_I8, PropertyTagTypeSRational },
2731         { VT_UI8, PropertyTagTypeRational },
2732         { VT_R4, PropertyTagTypeFloat },
2733         { VT_R8, PropertyTagTypeDouble },
2734         { VT_LPSTR, PropertyTagTypeASCII },
2735         { VT_BLOB, PropertyTagTypeUndefined }
2736     };
2737     UINT i;
2738     for (i = 0; i < sizeof(vt2type)/sizeof(vt2type[0]); i++)
2739     {
2740         if (vt2type[i].vt == vt) return vt2type[i].type;
2741     }
2742     FIXME("not supported variant type %u\n", vt);
2743     return 0;
2744 }
2745
2746 static GpStatus propvariant_to_item(PROPVARIANT *value, PropertyItem *item,
2747                                     UINT size, PROPID id)
2748 {
2749     UINT item_size, item_type;
2750
2751     item_size = propvariant_size(value);
2752     if (size != item_size + sizeof(PropertyItem)) return InvalidParameter;
2753
2754     item_type = vt_to_itemtype(value->vt & ~VT_VECTOR);
2755     if (!item_type) return InvalidParameter;
2756
2757     item->value = item + 1;
2758
2759     switch (value->vt & ~VT_VECTOR)
2760     {
2761     case VT_I1:
2762     case VT_UI1:
2763         if (!(value->vt & VT_VECTOR))
2764             *(BYTE *)item->value = value->u.bVal;
2765         else
2766             memcpy(item->value, value->u.caub.pElems, item_size);
2767         break;
2768     case VT_I2:
2769     case VT_UI2:
2770         if (!(value->vt & VT_VECTOR))
2771             *(USHORT *)item->value = value->u.uiVal;
2772         else
2773             memcpy(item->value, value->u.caui.pElems, item_size);
2774         break;
2775     case VT_I4:
2776     case VT_UI4:
2777     case VT_R4:
2778         if (!(value->vt & VT_VECTOR))
2779             *(ULONG *)item->value = value->u.ulVal;
2780         else
2781             memcpy(item->value, value->u.caul.pElems, item_size);
2782         break;
2783     case VT_I8:
2784     case VT_UI8:
2785     case VT_R8:
2786         if (!(value->vt & VT_VECTOR))
2787             *(ULONGLONG *)item->value = value->u.uhVal.QuadPart;
2788         else
2789             memcpy(item->value, value->u.cauh.pElems, item_size);
2790         break;
2791     case VT_LPSTR:
2792         memcpy(item->value, value->u.pszVal, item_size);
2793         break;
2794     case VT_BLOB:
2795         memcpy(item->value, value->u.blob.pBlobData, item_size);
2796         break;
2797     default:
2798         FIXME("not supported variant type %d\n", value->vt);
2799         return InvalidParameter;
2800     }
2801
2802     item->length = item_size;
2803     item->type = item_type;
2804     item->id = id;
2805
2806     return Ok;
2807 }
2808
2809 GpStatus WINGDIPAPI GdipGetPropertyItem(GpImage *image, PROPID propid, UINT size,
2810                                         PropertyItem *buffer)
2811 {
2812     GpStatus stat;
2813     HRESULT hr;
2814     IWICMetadataReader *reader;
2815     PROPVARIANT id, value;
2816
2817     TRACE("(%p,%#x,%u,%p)\n", image, propid, size, buffer);
2818
2819     if (!image || !buffer) return InvalidParameter;
2820
2821     if (image->type != ImageTypeBitmap)
2822     {
2823         FIXME("Not implemented for type %d\n", image->type);
2824         return NotImplemented;
2825     }
2826
2827     if (((GpBitmap *)image)->prop_item)
2828     {
2829         UINT i;
2830
2831         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2832         {
2833             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2834             {
2835                 if (size != sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length)
2836                     return InvalidParameter;
2837
2838                 *buffer = ((GpBitmap *)image)->prop_item[i];
2839                 buffer->value = buffer + 1;
2840                 memcpy(buffer->value, ((GpBitmap *)image)->prop_item[i].value, buffer->length);
2841                 return Ok;
2842             }
2843         }
2844
2845         return PropertyNotFound;
2846     }
2847
2848     reader = ((GpBitmap *)image)->metadata_reader;
2849     if (!reader) return PropertyNotFound;
2850
2851     id.vt = VT_UI2;
2852     id.u.uiVal = propid;
2853     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2854     if (FAILED(hr)) return PropertyNotFound;
2855
2856     stat = propvariant_to_item(&value, buffer, size, propid);
2857     PropVariantClear(&value);
2858
2859     return stat;
2860 }
2861
2862 GpStatus WINGDIPAPI GdipGetPropertySize(GpImage *image, UINT *size, UINT *count)
2863 {
2864     HRESULT hr;
2865     IWICMetadataReader *reader;
2866     IWICEnumMetadataItem *enumerator;
2867     UINT prop_count, prop_size, i;
2868     PROPVARIANT id, value;
2869
2870     TRACE("(%p,%p,%p)\n", image, size, count);
2871
2872     if (!image || !size || !count) return InvalidParameter;
2873
2874     if (image->type != ImageTypeBitmap)
2875     {
2876         FIXME("Not implemented for type %d\n", image->type);
2877         return NotImplemented;
2878     }
2879
2880     if (((GpBitmap *)image)->prop_item)
2881     {
2882         *count = ((GpBitmap *)image)->prop_count;
2883         *size = 0;
2884
2885         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2886         {
2887             *size += sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2888         }
2889
2890         return Ok;
2891     }
2892
2893     reader = ((GpBitmap *)image)->metadata_reader;
2894     if (!reader) return PropertyNotFound;
2895
2896     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2897     if (FAILED(hr)) return hresult_to_status(hr);
2898
2899     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2900     if (FAILED(hr)) return hresult_to_status(hr);
2901
2902     IWICEnumMetadataItem_Reset(enumerator);
2903
2904     prop_size = 0;
2905
2906     PropVariantInit(&id);
2907     PropVariantInit(&value);
2908
2909     for (i = 0; i < prop_count; i++)
2910     {
2911         UINT items_returned, item_size;
2912
2913         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2914         if (hr != S_OK) break;
2915
2916         item_size = propvariant_size(&value);
2917         if (item_size) prop_size += sizeof(PropertyItem) + item_size;
2918
2919         PropVariantClear(&id);
2920         PropVariantClear(&value);
2921     }
2922
2923     IWICEnumMetadataItem_Release(enumerator);
2924
2925     if (hr != S_OK) return PropertyNotFound;
2926
2927     *count = prop_count;
2928     *size = prop_size;
2929     return Ok;
2930 }
2931
2932 GpStatus WINGDIPAPI GdipGetAllPropertyItems(GpImage *image, UINT size,
2933                                             UINT count, PropertyItem *buf)
2934 {
2935     GpStatus status;
2936     HRESULT hr;
2937     IWICMetadataReader *reader;
2938     IWICEnumMetadataItem *enumerator;
2939     UINT prop_count, prop_size, i;
2940     PROPVARIANT id, value;
2941     char *item_value;
2942
2943     TRACE("(%p,%u,%u,%p)\n", image, size, count, buf);
2944
2945     if (!image || !buf) return InvalidParameter;
2946
2947     if (image->type != ImageTypeBitmap)
2948     {
2949         FIXME("Not implemented for type %d\n", image->type);
2950         return NotImplemented;
2951     }
2952
2953     status = GdipGetPropertySize(image, &prop_size, &prop_count);
2954     if (status != Ok) return status;
2955
2956     if (prop_count != count || prop_size != size) return InvalidParameter;
2957
2958     if (((GpBitmap *)image)->prop_item)
2959     {
2960         memcpy(buf, ((GpBitmap *)image)->prop_item, prop_size);
2961
2962         item_value = (char *)(buf + prop_count);
2963
2964         for (i = 0; i < prop_count; i++)
2965         {
2966             buf[i].value = item_value;
2967             item_value += buf[i].length;
2968         }
2969
2970         return Ok;
2971     }
2972
2973     reader = ((GpBitmap *)image)->metadata_reader;
2974     if (!reader) return PropertyNotFound;
2975
2976     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2977     if (FAILED(hr)) return hresult_to_status(hr);
2978
2979     IWICEnumMetadataItem_Reset(enumerator);
2980
2981     item_value = (char *)(buf + prop_count);
2982
2983     PropVariantInit(&id);
2984     PropVariantInit(&value);
2985
2986     for (i = 0; i < prop_count; i++)
2987     {
2988         PropertyItem *item;
2989         UINT items_returned, item_size;
2990
2991         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2992         if (hr != S_OK) break;
2993
2994         if (id.vt != VT_UI2)
2995         {
2996             FIXME("not supported propvariant type for id: %u\n", id.vt);
2997             continue;
2998         }
2999
3000         item_size = propvariant_size(&value);
3001         if (item_size)
3002         {
3003             item = HeapAlloc(GetProcessHeap(), 0, item_size + sizeof(*item));
3004
3005             propvariant_to_item(&value, item, item_size + sizeof(*item), id.u.uiVal);
3006             buf[i].id = item->id;
3007             buf[i].type = item->type;
3008             buf[i].length = item_size;
3009             buf[i].value = item_value;
3010             memcpy(item_value, item->value, item_size);
3011             item_value += item_size;
3012
3013             HeapFree(GetProcessHeap(), 0, item);
3014         }
3015
3016         PropVariantClear(&id);
3017         PropVariantClear(&value);
3018     }
3019
3020     IWICEnumMetadataItem_Release(enumerator);
3021
3022     if (hr != S_OK) return PropertyNotFound;
3023
3024     return Ok;
3025 }
3026
3027 struct image_format_dimension
3028 {
3029     const GUID *format;
3030     const GUID *dimension;
3031 };
3032
3033 static const struct image_format_dimension image_format_dimensions[] =
3034 {
3035     {&ImageFormatGIF, &FrameDimensionTime},
3036     {&ImageFormatIcon, &FrameDimensionResolution},
3037     {NULL}
3038 };
3039
3040 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
3041     GDIPCONST GUID* dimensionID, UINT* count)
3042 {
3043     TRACE("(%p,%s,%p)\n", image, debugstr_guid(dimensionID), count);
3044
3045     if(!image || !count)
3046         return InvalidParameter;
3047
3048     if (!dimensionID ||
3049         IsEqualGUID(dimensionID, &image->format) ||
3050         IsEqualGUID(dimensionID, &FrameDimensionPage) ||
3051         IsEqualGUID(dimensionID, &FrameDimensionTime))
3052     {
3053         *count = image->frame_count;
3054         return Ok;
3055     }
3056
3057     return InvalidParameter;
3058 }
3059
3060 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsCount(GpImage *image,
3061     UINT* count)
3062 {
3063     TRACE("(%p, %p)\n", image, count);
3064
3065     /* Native gdiplus 1.1 does not yet support multiple frame dimensions. */
3066
3067     if(!image || !count)
3068         return InvalidParameter;
3069
3070     *count = 1;
3071
3072     return Ok;
3073 }
3074
3075 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
3076     GUID* dimensionIDs, UINT count)
3077 {
3078     int i;
3079     const GUID *result=NULL;
3080
3081     TRACE("(%p,%p,%u)\n", image, dimensionIDs, count);
3082
3083     if(!image || !dimensionIDs || count != 1)
3084         return InvalidParameter;
3085
3086     for (i=0; image_format_dimensions[i].format; i++)
3087     {
3088         if (IsEqualGUID(&image->format, image_format_dimensions[i].format))
3089         {
3090             result = image_format_dimensions[i].dimension;
3091             break;
3092         }
3093     }
3094
3095     if (!result)
3096         result = &FrameDimensionPage;
3097
3098     memcpy(dimensionIDs, result, sizeof(GUID));
3099
3100     return Ok;
3101 }
3102
3103 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
3104                                           GpImage **image)
3105 {
3106     GpStatus stat;
3107     IStream *stream;
3108
3109     TRACE("(%s) %p\n", debugstr_w(filename), image);
3110
3111     if (!filename || !image)
3112         return InvalidParameter;
3113
3114     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
3115
3116     if (stat != Ok)
3117         return stat;
3118
3119     stat = GdipLoadImageFromStream(stream, image);
3120
3121     IStream_Release(stream);
3122
3123     return stat;
3124 }
3125
3126 /* FIXME: no icm handling */
3127 GpStatus WINGDIPAPI GdipLoadImageFromFileICM(GDIPCONST WCHAR* filename,GpImage **image)
3128 {
3129     TRACE("(%s) %p\n", debugstr_w(filename), image);
3130
3131     return GdipLoadImageFromFile(filename, image);
3132 }
3133
3134 static void add_property(GpBitmap *bitmap, PropertyItem *item)
3135 {
3136     UINT prop_size, prop_count;
3137     PropertyItem *prop_item;
3138
3139     if (bitmap->prop_item == NULL)
3140     {
3141         prop_size = prop_count = 0;
3142         prop_item = GdipAlloc(item->length + sizeof(PropertyItem));
3143         if (!prop_item) return;
3144     }
3145     else
3146     {
3147         UINT i;
3148         char *item_value;
3149
3150         GdipGetPropertySize((GpImage *)bitmap, &prop_size, &prop_count);
3151
3152         prop_item = GdipAlloc(prop_size + item->length + sizeof(PropertyItem));
3153         if (!prop_item) return;
3154         memcpy(prop_item, bitmap->prop_item, sizeof(PropertyItem) * bitmap->prop_count);
3155         prop_size -= sizeof(PropertyItem) * bitmap->prop_count;
3156         memcpy(prop_item + prop_count + 1, bitmap->prop_item + prop_count, prop_size);
3157
3158         item_value = (char *)(prop_item + prop_count + 1);
3159
3160         for (i = 0; i < prop_count; i++)
3161         {
3162             prop_item[i].value = item_value;
3163             item_value += prop_item[i].length;
3164         }
3165     }
3166
3167     prop_item[prop_count].id = item->id;
3168     prop_item[prop_count].type = item->type;
3169     prop_item[prop_count].length = item->length;
3170     prop_item[prop_count].value = (char *)(prop_item + prop_count + 1) + prop_size;
3171     memcpy(prop_item[prop_count].value, item->value, item->length);
3172
3173     GdipFree(bitmap->prop_item);
3174     bitmap->prop_item = prop_item;
3175     bitmap->prop_count++;
3176 }
3177
3178 static BOOL get_bool_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3179 {
3180     HRESULT hr;
3181     GUID format;
3182     PROPVARIANT id, value;
3183     BOOL ret = FALSE;
3184
3185     IWICMetadataReader_GetMetadataFormat(reader, &format);
3186     if (!IsEqualGUID(&format, guid)) return FALSE;
3187
3188     PropVariantInit(&id);
3189     PropVariantInit(&value);
3190
3191     id.vt = VT_LPWSTR;
3192     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3193     if (!id.u.pwszVal) return FALSE;
3194     lstrcpyW(id.u.pwszVal, prop_name);
3195     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3196     if (hr == S_OK && value.vt == VT_BOOL)
3197         ret = value.u.boolVal;
3198
3199     PropVariantClear(&id);
3200     PropVariantClear(&value);
3201
3202     return ret;
3203 }
3204
3205 static PropertyItem *get_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3206 {
3207     HRESULT hr;
3208     GUID format;
3209     PROPVARIANT id, value;
3210     PropertyItem *item = NULL;
3211
3212     IWICMetadataReader_GetMetadataFormat(reader, &format);
3213     if (!IsEqualGUID(&format, guid)) return NULL;
3214
3215     PropVariantInit(&id);
3216     PropVariantInit(&value);
3217
3218     id.vt = VT_LPWSTR;
3219     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3220     if (!id.u.pwszVal) return NULL;
3221     lstrcpyW(id.u.pwszVal, prop_name);
3222     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3223     if (hr == S_OK)
3224     {
3225         UINT item_size = propvariant_size(&value);
3226         if (item_size)
3227         {
3228             item_size += sizeof(*item);
3229             item = GdipAlloc(item_size);
3230             if (propvariant_to_item(&value, item, item_size, 0) != Ok)
3231             {
3232                 GdipFree(item);
3233                 item = NULL;
3234             }
3235         }
3236     }
3237
3238     PropVariantClear(&id);
3239     PropVariantClear(&value);
3240
3241     return item;
3242 }
3243
3244 static PropertyItem *get_gif_comment(IWICMetadataReader *reader)
3245 {
3246     static const WCHAR textentryW[] = { 'T','e','x','t','E','n','t','r','y',0 };
3247     PropertyItem *comment;
3248
3249     comment = get_property(reader, &GUID_MetadataFormatGifComment, textentryW);
3250     if (comment)
3251         comment->id = PropertyTagExifUserComment;
3252
3253     return comment;
3254 }
3255
3256 static PropertyItem *get_gif_loopcount(IWICMetadataReader *reader)
3257 {
3258     static const WCHAR applicationW[] = { 'A','p','p','l','i','c','a','t','i','o','n',0 };
3259     static const WCHAR dataW[] = { 'D','a','t','a',0 };
3260     PropertyItem *appext = NULL, *appdata = NULL, *loop = NULL;
3261
3262     appext = get_property(reader, &GUID_MetadataFormatAPE, applicationW);
3263     if (appext)
3264     {
3265         if (appext->type == PropertyTagTypeByte && appext->length == 11 &&
3266             (!memcmp(appext->value, "NETSCAPE2.0", 11) || !memcmp(appext->value, "ANIMEXTS1.0", 11)))
3267         {
3268             appdata = get_property(reader, &GUID_MetadataFormatAPE, dataW);
3269             if (appdata)
3270             {
3271                 if (appdata->type == PropertyTagTypeByte && appdata->length == 4)
3272                 {
3273                     BYTE *data = appdata->value;
3274                     if (data[0] == 3 && data[1] == 1)
3275                     {
3276                         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3277                         if (loop)
3278                         {
3279                             loop->type = PropertyTagTypeShort;
3280                             loop->id = PropertyTagLoopCount;
3281                             loop->length = sizeof(SHORT);
3282                             loop->value = loop + 1;
3283                             *(SHORT *)loop->value = data[2] | (data[3] << 8);
3284                         }
3285                     }
3286                 }
3287             }
3288         }
3289     }
3290
3291     GdipFree(appext);
3292     GdipFree(appdata);
3293
3294     return loop;
3295 }
3296
3297 static PropertyItem *get_gif_background(IWICMetadataReader *reader)
3298 {
3299     static const WCHAR backgroundW[] = { 'B','a','c','k','g','r','o','u','n','d','C','o','l','o','r','I','n','d','e','x',0 };
3300     PropertyItem *background;
3301
3302     background = get_property(reader, &GUID_MetadataFormatLSD, backgroundW);
3303     if (background)
3304         background->id = PropertyTagIndexBackground;
3305
3306     return background;
3307 }
3308
3309 static PropertyItem *get_gif_palette(IWICBitmapDecoder *decoder, IWICMetadataReader *reader)
3310 {
3311     static const WCHAR global_flagW[] = { 'G','l','o','b','a','l','C','o','l','o','r','T','a','b','l','e','F','l','a','g',0 };
3312     HRESULT hr;
3313     IWICImagingFactory *factory;
3314     IWICPalette *palette;
3315     UINT count = 0;
3316     WICColor colors[256];
3317
3318     if (!get_bool_property(reader, &GUID_MetadataFormatLSD, global_flagW))
3319         return NULL;
3320
3321     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
3322                           &IID_IWICImagingFactory, (void **)&factory);
3323     if (hr != S_OK) return NULL;
3324
3325     hr = IWICImagingFactory_CreatePalette(factory, &palette);
3326     if (hr == S_OK)
3327     {
3328         hr = IWICBitmapDecoder_CopyPalette(decoder, palette);
3329         if (hr == S_OK)
3330             IWICPalette_GetColors(palette, 256, colors, &count);
3331
3332         IWICPalette_Release(palette);
3333     }
3334
3335     IWICImagingFactory_Release(factory);
3336
3337     if (count)
3338     {
3339         PropertyItem *pal;
3340         UINT i;
3341         BYTE *rgb;
3342
3343         pal = GdipAlloc(sizeof(*pal) + count * 3);
3344         if (!pal) return NULL;
3345         pal->type = PropertyTagTypeByte;
3346         pal->id = PropertyTagGlobalPalette;
3347         pal->value = pal + 1;
3348         pal->length = count * 3;
3349
3350         rgb = pal->value;
3351
3352         for (i = 0; i < count; i++)
3353         {
3354             rgb[i*3] = (colors[i] >> 16) & 0xff;
3355             rgb[i*3 + 1] = (colors[i] >> 8) & 0xff;
3356             rgb[i*3 + 2] = colors[i] & 0xff;
3357         }
3358
3359         return pal;
3360     }
3361
3362     return NULL;
3363 }
3364
3365 static PropertyItem *get_gif_transparent_idx(IWICMetadataReader *reader)
3366 {
3367     static const WCHAR transparency_flagW[] = { 'T','r','a','n','s','p','a','r','e','n','c','y','F','l','a','g',0 };
3368     static const WCHAR colorW[] = { 'T','r','a','n','s','p','a','r','e','n','t','C','o','l','o','r','I','n','d','e','x',0 };
3369     PropertyItem *index = NULL;
3370
3371     if (get_bool_property(reader, &GUID_MetadataFormatGCE, transparency_flagW))
3372     {
3373         index = get_property(reader, &GUID_MetadataFormatGCE, colorW);
3374         if (index)
3375             index->id = PropertyTagIndexTransparent;
3376     }
3377     return index;
3378 }
3379
3380 static LONG get_gif_frame_delay(IWICBitmapFrameDecode *frame)
3381 {
3382     static const WCHAR delayW[] = { 'D','e','l','a','y',0 };
3383     HRESULT hr;
3384     IWICMetadataBlockReader *block_reader;
3385     IWICMetadataReader *reader;
3386     UINT block_count, i;
3387     PropertyItem *delay;
3388     LONG value = 0;
3389
3390     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3391     if (hr == S_OK)
3392     {
3393         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3394         if (hr == S_OK)
3395         {
3396             for (i = 0; i < block_count; i++)
3397             {
3398                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3399                 if (hr == S_OK)
3400                 {
3401                     delay = get_property(reader, &GUID_MetadataFormatGCE, delayW);
3402                     if (delay)
3403                     {
3404                         if (delay->type == PropertyTagTypeShort && delay->length == 2)
3405                             value = *(SHORT *)delay->value;
3406
3407                         GdipFree(delay);
3408                     }
3409                     IWICMetadataReader_Release(reader);
3410                 }
3411             }
3412         }
3413         IWICMetadataBlockReader_Release(block_reader);
3414     }
3415
3416     return value;
3417 }
3418
3419 static void gif_metadata_reader(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT active_frame)
3420 {
3421     HRESULT hr;
3422     IWICBitmapFrameDecode *frame;
3423     IWICMetadataBlockReader *block_reader;
3424     IWICMetadataReader *reader;
3425     UINT frame_count, block_count, i;
3426     PropertyItem *delay = NULL, *comment = NULL, *background = NULL;
3427     PropertyItem *transparent_idx = NULL, *loop = NULL, *palette = NULL;
3428
3429     IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3430     if (frame_count > 1)
3431     {
3432         delay = GdipAlloc(sizeof(*delay) + frame_count * sizeof(LONG));
3433         if (delay)
3434         {
3435             LONG *value;
3436
3437             delay->type = PropertyTagTypeLong;
3438             delay->id = PropertyTagFrameDelay;
3439             delay->length = frame_count * sizeof(LONG);
3440             delay->value = delay + 1;
3441
3442             value = delay->value;
3443
3444             for (i = 0; i < frame_count; i++)
3445             {
3446                 hr = IWICBitmapDecoder_GetFrame(decoder, i, &frame);
3447                 if (hr == S_OK)
3448                 {
3449                     value[i] = get_gif_frame_delay(frame);
3450                     IWICBitmapFrameDecode_Release(frame);
3451                 }
3452                 else value[i] = 0;
3453             }
3454         }
3455     }
3456
3457     hr = IWICBitmapDecoder_QueryInterface(decoder, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3458     if (hr == S_OK)
3459     {
3460         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3461         if (hr == S_OK)
3462         {
3463             for (i = 0; i < block_count; i++)
3464             {
3465                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3466                 if (hr == S_OK)
3467                 {
3468                     if (!comment)
3469                         comment = get_gif_comment(reader);
3470
3471                     if (frame_count > 1 && !loop)
3472                         loop = get_gif_loopcount(reader);
3473
3474                     if (!background)
3475                         background = get_gif_background(reader);
3476
3477                     if (!palette)
3478                         palette = get_gif_palette(decoder, reader);
3479
3480                     IWICMetadataReader_Release(reader);
3481                 }
3482             }
3483         }
3484         IWICMetadataBlockReader_Release(block_reader);
3485     }
3486
3487     if (frame_count > 1 && !loop)
3488     {
3489         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3490         if (loop)
3491         {
3492             loop->type = PropertyTagTypeShort;
3493             loop->id = PropertyTagLoopCount;
3494             loop->length = sizeof(SHORT);
3495             loop->value = loop + 1;
3496             *(SHORT *)loop->value = 1;
3497         }
3498     }
3499
3500     if (delay) add_property(bitmap, delay);
3501     if (comment) add_property(bitmap, comment);
3502     if (loop) add_property(bitmap, loop);
3503     if (palette) add_property(bitmap, palette);
3504     if (background) add_property(bitmap, background);
3505
3506     GdipFree(delay);
3507     GdipFree(comment);
3508     GdipFree(loop);
3509     GdipFree(palette);
3510     GdipFree(background);
3511
3512     /* Win7 gdiplus always returns transparent color index from frame 0 */
3513     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
3514     if (hr != S_OK) return;
3515
3516     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3517     if (hr == S_OK)
3518     {
3519         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3520         if (hr == S_OK)
3521         {
3522             for (i = 0; i < block_count; i++)
3523             {
3524                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3525                 if (hr == S_OK)
3526                 {
3527                     if (!transparent_idx)
3528                         transparent_idx = get_gif_transparent_idx(reader);
3529
3530                     IWICMetadataReader_Release(reader);
3531                 }
3532             }
3533         }
3534         IWICMetadataBlockReader_Release(block_reader);
3535     }
3536
3537     if (transparent_idx) add_property(bitmap, transparent_idx);
3538     GdipFree(transparent_idx);
3539
3540     IWICBitmapFrameDecode_Release(frame);
3541 }
3542
3543 typedef void (*metadata_reader_func)(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT frame);
3544
3545 static GpStatus decode_image_wic(IStream *stream, GDIPCONST CLSID *clsid,
3546     UINT active_frame, metadata_reader_func metadata_reader, GpImage **image)
3547 {
3548     GpStatus status=Ok;
3549     GpBitmap *bitmap;
3550     HRESULT hr;
3551     IWICBitmapDecoder *decoder;
3552     IWICBitmapFrameDecode *frame;
3553     IWICBitmapSource *source=NULL;
3554     IWICMetadataBlockReader *block_reader;
3555     WICPixelFormatGUID wic_format;
3556     PixelFormat gdip_format=0;
3557     ColorPalette *palette = NULL;
3558     WICBitmapPaletteType palette_type = WICBitmapPaletteTypeFixedHalftone256;
3559     int i;
3560     UINT width, height, frame_count;
3561     BitmapData lockeddata;
3562     WICRect wrc;
3563     HRESULT initresult;
3564
3565     TRACE("%p,%s,%u,%p\n", stream, wine_dbgstr_guid(clsid), active_frame, image);
3566
3567     initresult = CoInitialize(NULL);
3568
3569     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
3570         &IID_IWICBitmapDecoder, (void**)&decoder);
3571     if (FAILED(hr)) goto end;
3572
3573     hr = IWICBitmapDecoder_Initialize(decoder, stream, WICDecodeMetadataCacheOnLoad);
3574     if (SUCCEEDED(hr))
3575     {
3576         IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3577         hr = IWICBitmapDecoder_GetFrame(decoder, active_frame, &frame);
3578     }
3579
3580     if (SUCCEEDED(hr)) /* got frame */
3581     {
3582         hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &wic_format);
3583
3584         if (SUCCEEDED(hr))
3585         {
3586             IWICBitmapSource *bmp_source;
3587             IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICBitmapSource, (void **)&bmp_source);
3588
3589             for (i=0; pixel_formats[i].wic_format; i++)
3590             {
3591                 if (IsEqualGUID(&wic_format, pixel_formats[i].wic_format))
3592                 {
3593                     source = bmp_source;
3594                     gdip_format = pixel_formats[i].gdip_format;
3595                     palette_type = pixel_formats[i].palette_type;
3596                     break;
3597                 }
3598             }
3599             if (!source)
3600             {
3601                 /* unknown format; fall back on 32bppARGB */
3602                 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, bmp_source, &source);
3603                 gdip_format = PixelFormat32bppARGB;
3604                 IWICBitmapSource_Release(bmp_source);
3605             }
3606             TRACE("%s => %#x\n", wine_dbgstr_guid(&wic_format), gdip_format);
3607         }
3608
3609         if (SUCCEEDED(hr)) /* got source */
3610         {
3611             hr = IWICBitmapSource_GetSize(source, &width, &height);
3612
3613             if (SUCCEEDED(hr))
3614                 status = GdipCreateBitmapFromScan0(width, height, 0, gdip_format,
3615                     NULL, &bitmap);
3616
3617             if (SUCCEEDED(hr) && status == Ok) /* created bitmap */
3618             {
3619                 status = GdipBitmapLockBits(bitmap, NULL, ImageLockModeWrite,
3620                     gdip_format, &lockeddata);
3621                 if (status == Ok) /* locked bitmap */
3622                 {
3623                     wrc.X = 0;
3624                     wrc.Width = width;
3625                     wrc.Height = 1;
3626                     for (i=0; i<height; i++)
3627                     {
3628                         wrc.Y = i;
3629                         hr = IWICBitmapSource_CopyPixels(source, &wrc, abs(lockeddata.Stride),
3630                             abs(lockeddata.Stride), (BYTE*)lockeddata.Scan0+lockeddata.Stride*i);
3631                         if (FAILED(hr)) break;
3632                     }
3633
3634                     GdipBitmapUnlockBits(bitmap, &lockeddata);
3635                 }
3636
3637                 if (SUCCEEDED(hr) && status == Ok)
3638                     *image = (GpImage*)bitmap;
3639                 else
3640                 {
3641                     *image = NULL;
3642                     GdipDisposeImage((GpImage*)bitmap);
3643                 }
3644
3645                 if (SUCCEEDED(hr) && status == Ok)
3646                 {
3647                     double dpix, dpiy;
3648                     hr = IWICBitmapSource_GetResolution(source, &dpix, &dpiy);
3649                     if (SUCCEEDED(hr))
3650                     {
3651                         bitmap->image.xres = dpix;
3652                         bitmap->image.yres = dpiy;
3653                     }
3654                     hr = S_OK;
3655                 }
3656             }
3657
3658             IWICBitmapSource_Release(source);
3659         }
3660
3661         if (SUCCEEDED(hr)) {
3662             bitmap->metadata_reader = NULL;
3663
3664             if (metadata_reader)
3665                 metadata_reader(bitmap, decoder, active_frame);
3666             else if (IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader) == S_OK)
3667             {
3668                 UINT block_count = 0;
3669                 if (IWICMetadataBlockReader_GetCount(block_reader, &block_count) == S_OK && block_count)
3670                     IWICMetadataBlockReader_GetReaderByIndex(block_reader, 0, &bitmap->metadata_reader);
3671                 IWICMetadataBlockReader_Release(block_reader);
3672             }
3673
3674             palette = get_palette(frame, palette_type);
3675             IWICBitmapFrameDecode_Release(frame);
3676         }
3677     }
3678
3679     IWICBitmapDecoder_Release(decoder);
3680
3681 end:
3682     if (SUCCEEDED(initresult)) CoUninitialize();
3683
3684     if (FAILED(hr) && status == Ok) status = hresult_to_status(hr);
3685
3686     if (status == Ok)
3687     {
3688         /* Native GDI+ used to be smarter, but since Win7 it just sets these flags. */
3689         bitmap->image.flags |= ImageFlagsReadOnly|ImageFlagsHasRealPixelSize|ImageFlagsHasRealDPI|ImageFlagsColorSpaceRGB;
3690         bitmap->image.frame_count = frame_count;
3691         bitmap->image.current_frame = active_frame;
3692         bitmap->image.stream = stream;
3693         if (palette)
3694         {
3695             GdipFree(bitmap->image.palette);
3696             bitmap->image.palette = palette;
3697         }
3698         else
3699         {
3700             if (IsEqualGUID(&wic_format, &GUID_WICPixelFormatBlackWhite))
3701                 bitmap->image.palette->Flags = 0;
3702         }
3703         /* Pin the source stream */
3704         IStream_AddRef(stream);
3705         TRACE("=> %p\n", *image);
3706     }
3707
3708     return status;
3709 }
3710
3711 static GpStatus decode_image_icon(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3712 {
3713     return decode_image_wic(stream, &CLSID_WICIcoDecoder, active_frame, NULL, image);
3714 }
3715
3716 static GpStatus decode_image_bmp(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3717 {
3718     GpStatus status;
3719     GpBitmap* bitmap;
3720
3721     status = decode_image_wic(stream, &CLSID_WICBmpDecoder, active_frame, NULL, image);
3722
3723     bitmap = (GpBitmap*)*image;
3724
3725     if (status == Ok && bitmap->format == PixelFormat32bppARGB)
3726     {
3727         /* WIC supports bmp files with alpha, but gdiplus does not */
3728         bitmap->format = PixelFormat32bppRGB;
3729     }
3730
3731     return status;
3732 }
3733
3734 static GpStatus decode_image_jpeg(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3735 {
3736     return decode_image_wic(stream, &CLSID_WICJpegDecoder, active_frame, NULL, image);
3737 }
3738
3739 static GpStatus decode_image_png(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3740 {
3741     return decode_image_wic(stream, &CLSID_WICPngDecoder, active_frame, NULL, image);
3742 }
3743
3744 static GpStatus decode_image_gif(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3745 {
3746     return decode_image_wic(stream, &CLSID_WICGifDecoder, active_frame, gif_metadata_reader, image);
3747 }
3748
3749 static GpStatus decode_image_tiff(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3750 {
3751     return decode_image_wic(stream, &CLSID_WICTiffDecoder, active_frame, NULL, image);
3752 }
3753
3754 static GpStatus decode_image_olepicture_metafile(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3755 {
3756     IPicture *pic;
3757
3758     TRACE("%p %p\n", stream, image);
3759
3760     if(!stream || !image)
3761         return InvalidParameter;
3762
3763     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
3764         (LPVOID*) &pic) != S_OK){
3765         TRACE("Could not load picture\n");
3766         return GenericError;
3767     }
3768
3769     /* FIXME: missing initialization code */
3770     *image = GdipAlloc(sizeof(GpMetafile));
3771     if(!*image) return OutOfMemory;
3772     (*image)->type = ImageTypeMetafile;
3773     (*image)->stream = NULL;
3774     (*image)->picture = pic;
3775     (*image)->flags   = ImageFlagsNone;
3776     (*image)->frame_count = 1;
3777     (*image)->current_frame = 0;
3778     (*image)->palette = NULL;
3779
3780     TRACE("<-- %p\n", *image);
3781
3782     return Ok;
3783 }
3784
3785 typedef GpStatus (*encode_image_func)(GpImage *image, IStream* stream,
3786     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params);
3787
3788 typedef GpStatus (*decode_image_func)(IStream *stream, REFCLSID clsid, UINT active_frame, GpImage **image);
3789
3790 typedef struct image_codec {
3791     ImageCodecInfo info;
3792     encode_image_func encode_func;
3793     decode_image_func decode_func;
3794 } image_codec;
3795
3796 typedef enum {
3797     BMP,
3798     JPEG,
3799     GIF,
3800     TIFF,
3801     EMF,
3802     WMF,
3803     PNG,
3804     ICO,
3805     NUM_CODECS
3806 } ImageFormat;
3807
3808 static const struct image_codec codecs[NUM_CODECS];
3809
3810 static GpStatus get_decoder_info(IStream* stream, const struct image_codec **result)
3811 {
3812     BYTE signature[8];
3813     const BYTE *pattern, *mask;
3814     LARGE_INTEGER seek;
3815     HRESULT hr;
3816     UINT bytesread;
3817     int i, j, sig;
3818
3819     /* seek to the start of the stream */
3820     seek.QuadPart = 0;
3821     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3822     if (FAILED(hr)) return hresult_to_status(hr);
3823
3824     /* read the first 8 bytes */
3825     /* FIXME: This assumes all codecs have signatures <= 8 bytes in length */
3826     hr = IStream_Read(stream, signature, 8, &bytesread);
3827     if (FAILED(hr)) return hresult_to_status(hr);
3828     if (hr == S_FALSE || bytesread == 0) return GenericError;
3829
3830     for (i = 0; i < NUM_CODECS; i++) {
3831         if ((codecs[i].info.Flags & ImageCodecFlagsDecoder) &&
3832             bytesread >= codecs[i].info.SigSize)
3833         {
3834             for (sig=0; sig<codecs[i].info.SigCount; sig++)
3835             {
3836                 pattern = &codecs[i].info.SigPattern[codecs[i].info.SigSize*sig];
3837                 mask = &codecs[i].info.SigMask[codecs[i].info.SigSize*sig];
3838                 for (j=0; j<codecs[i].info.SigSize; j++)
3839                     if ((signature[j] & mask[j]) != pattern[j])
3840                         break;
3841                 if (j == codecs[i].info.SigSize)
3842                 {
3843                     *result = &codecs[i];
3844                     return Ok;
3845                 }
3846             }
3847         }
3848     }
3849
3850     TRACE("no match for %i byte signature %x %x %x %x %x %x %x %x\n", bytesread,
3851         signature[0],signature[1],signature[2],signature[3],
3852         signature[4],signature[5],signature[6],signature[7]);
3853
3854     return GenericError;
3855 }
3856
3857 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image, GDIPCONST GUID *dimensionID,
3858                                                UINT frame)
3859 {
3860     GpStatus stat;
3861     LARGE_INTEGER seek;
3862     HRESULT hr;
3863     const struct image_codec *codec = NULL;
3864     GpImage *new_image;
3865
3866     TRACE("(%p,%s,%u)\n", image, debugstr_guid(dimensionID), frame);
3867
3868     if (!image || !dimensionID)
3869         return InvalidParameter;
3870
3871     if (frame >= image->frame_count)
3872     {
3873         WARN("requested frame %u, but image has only %u\n", frame, image->frame_count);
3874         return InvalidParameter;
3875     }
3876
3877     if (image->type != ImageTypeBitmap && image->type != ImageTypeMetafile)
3878     {
3879         WARN("invalid image type %d\n", image->type);
3880         return InvalidParameter;
3881     }
3882
3883     if (image->current_frame == frame)
3884         return Ok;
3885
3886     if (!image->stream)
3887     {
3888         TRACE("image doesn't have an associated stream\n");
3889         return Ok;
3890     }
3891
3892     /* choose an appropriate image decoder */
3893     stat = get_decoder_info(image->stream, &codec);
3894     if (stat != Ok)
3895     {
3896         WARN("can't find decoder info\n");
3897         return stat;
3898     }
3899
3900     /* seek to the start of the stream */
3901     seek.QuadPart = 0;
3902     hr = IStream_Seek(image->stream, seek, STREAM_SEEK_SET, NULL);
3903     if (FAILED(hr))
3904         return hresult_to_status(hr);
3905
3906     /* call on the image decoder to do the real work */
3907     stat = codec->decode_func(image->stream, &codec->info.Clsid, frame, &new_image);
3908
3909     if (stat == Ok)
3910     {
3911         memcpy(&new_image->format, &codec->info.FormatID, sizeof(GUID));
3912         free_image_data(image);
3913         if (image->type == ImageTypeBitmap)
3914             *(GpBitmap *)image = *(GpBitmap *)new_image;
3915         else if (image->type == ImageTypeMetafile)
3916             *(GpMetafile *)image = *(GpMetafile *)new_image;
3917         new_image->type = ~0;
3918         GdipFree(new_image);
3919         return Ok;
3920     }
3921
3922     return stat;
3923 }
3924
3925 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream *stream, GpImage **image)
3926 {
3927     GpStatus stat;
3928     LARGE_INTEGER seek;
3929     HRESULT hr;
3930     const struct image_codec *codec=NULL;
3931
3932     /* choose an appropriate image decoder */
3933     stat = get_decoder_info(stream, &codec);
3934     if (stat != Ok) return stat;
3935
3936     /* seek to the start of the stream */
3937     seek.QuadPart = 0;
3938     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3939     if (FAILED(hr)) return hresult_to_status(hr);
3940
3941     /* call on the image decoder to do the real work */
3942     stat = codec->decode_func(stream, &codec->info.Clsid, 0, image);
3943
3944     /* take note of the original data format */
3945     if (stat == Ok)
3946     {
3947         memcpy(&(*image)->format, &codec->info.FormatID, sizeof(GUID));
3948         return Ok;
3949     }
3950
3951     return stat;
3952 }
3953
3954 /* FIXME: no ICM */
3955 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
3956 {
3957     TRACE("%p %p\n", stream, image);
3958
3959     return GdipLoadImageFromStream(stream, image);
3960 }
3961
3962 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
3963 {
3964     static int calls;
3965
3966     TRACE("(%p,%u)\n", image, propId);
3967
3968     if(!image)
3969         return InvalidParameter;
3970
3971     if(!(calls++))
3972         FIXME("not implemented\n");
3973
3974     return NotImplemented;
3975 }
3976
3977 GpStatus WINGDIPAPI GdipSetPropertyItem(GpImage *image, GDIPCONST PropertyItem* item)
3978 {
3979     static int calls;
3980
3981     if (!image || !item) return InvalidParameter;
3982
3983     TRACE("(%p,%p:%#x,%u,%u,%p)\n", image, item, item->id, item->type, item->length, item->value);
3984
3985     if(!(calls++))
3986         FIXME("not implemented\n");
3987
3988     return Ok;
3989 }
3990
3991 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
3992                                         GDIPCONST CLSID *clsidEncoder,
3993                                         GDIPCONST EncoderParameters *encoderParams)
3994 {
3995     GpStatus stat;
3996     IStream *stream;
3997
3998     TRACE("%p (%s) %p %p\n", image, debugstr_w(filename), clsidEncoder, encoderParams);
3999
4000     if (!image || !filename|| !clsidEncoder)
4001         return InvalidParameter;
4002
4003     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
4004     if (stat != Ok)
4005         return GenericError;
4006
4007     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
4008
4009     IStream_Release(stream);
4010     return stat;
4011 }
4012
4013 /*************************************************************************
4014  * Encoding functions -
4015  *   These functions encode an image in different image file formats.
4016  */
4017 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
4018 #define BITMAP_FORMAT_JPEG  0xd8ff
4019 #define BITMAP_FORMAT_GIF   0x4947
4020 #define BITMAP_FORMAT_PNG   0x5089
4021 #define BITMAP_FORMAT_APM   0xcdd7
4022
4023 static GpStatus encode_image_WIC(GpImage *image, IStream* stream,
4024     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4025 {
4026     GpStatus stat;
4027     GpBitmap *bitmap;
4028     IWICBitmapEncoder *encoder;
4029     IWICBitmapFrameEncode *frameencode;
4030     IPropertyBag2 *encoderoptions;
4031     HRESULT hr;
4032     UINT width, height;
4033     PixelFormat gdipformat=0;
4034     WICPixelFormatGUID wicformat;
4035     GpRect rc;
4036     BitmapData lockeddata;
4037     HRESULT initresult;
4038     UINT i;
4039
4040     if (image->type != ImageTypeBitmap)
4041         return GenericError;
4042
4043     bitmap = (GpBitmap*)image;
4044
4045     GdipGetImageWidth(image, &width);
4046     GdipGetImageHeight(image, &height);
4047
4048     rc.X = 0;
4049     rc.Y = 0;
4050     rc.Width = width;
4051     rc.Height = height;
4052
4053     initresult = CoInitialize(NULL);
4054
4055     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
4056         &IID_IWICBitmapEncoder, (void**)&encoder);
4057     if (FAILED(hr))
4058     {
4059         if (SUCCEEDED(initresult)) CoUninitialize();
4060         return hresult_to_status(hr);
4061     }
4062
4063     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
4064
4065     if (SUCCEEDED(hr))
4066     {
4067         hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frameencode, &encoderoptions);
4068     }
4069
4070     if (SUCCEEDED(hr)) /* created frame */
4071     {
4072         hr = IWICBitmapFrameEncode_Initialize(frameencode, encoderoptions);
4073
4074         if (SUCCEEDED(hr))
4075             hr = IWICBitmapFrameEncode_SetSize(frameencode, width, height);
4076
4077         if (SUCCEEDED(hr))
4078             hr = IWICBitmapFrameEncode_SetResolution(frameencode, image->xres, image->yres);
4079
4080         if (SUCCEEDED(hr))
4081         {
4082             for (i=0; pixel_formats[i].wic_format; i++)
4083             {
4084                 if (pixel_formats[i].gdip_format == bitmap->format)
4085                 {
4086                     memcpy(&wicformat, pixel_formats[i].wic_format, sizeof(GUID));
4087                     gdipformat = bitmap->format;
4088                     break;
4089                 }
4090             }
4091             if (!gdipformat)
4092             {
4093                 memcpy(&wicformat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
4094                 gdipformat = PixelFormat32bppARGB;
4095             }
4096
4097             hr = IWICBitmapFrameEncode_SetPixelFormat(frameencode, &wicformat);
4098         }
4099
4100         if (SUCCEEDED(hr))
4101         {
4102             stat = GdipBitmapLockBits(bitmap, &rc, ImageLockModeRead, gdipformat,
4103                 &lockeddata);
4104
4105             if (stat == Ok)
4106             {
4107                 UINT row_size = (lockeddata.Width * PIXELFORMATBPP(gdipformat) + 7)/8;
4108                 BYTE *row;
4109
4110                 /* write one row at a time in case stride is negative */
4111                 row = lockeddata.Scan0;
4112                 for (i=0; i<lockeddata.Height; i++)
4113                 {
4114                     hr = IWICBitmapFrameEncode_WritePixels(frameencode, 1, row_size, row_size, row);
4115                     if (FAILED(hr)) break;
4116                     row += lockeddata.Stride;
4117                 }
4118
4119                 GdipBitmapUnlockBits(bitmap, &lockeddata);
4120             }
4121             else
4122                 hr = E_FAIL;
4123         }
4124
4125         if (SUCCEEDED(hr))
4126             hr = IWICBitmapFrameEncode_Commit(frameencode);
4127
4128         IWICBitmapFrameEncode_Release(frameencode);
4129         IPropertyBag2_Release(encoderoptions);
4130     }
4131
4132     if (SUCCEEDED(hr))
4133         hr = IWICBitmapEncoder_Commit(encoder);
4134
4135     IWICBitmapEncoder_Release(encoder);
4136
4137     if (SUCCEEDED(initresult)) CoUninitialize();
4138
4139     return hresult_to_status(hr);
4140 }
4141
4142 static GpStatus encode_image_BMP(GpImage *image, IStream* stream,
4143     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4144 {
4145     return encode_image_WIC(image, stream, &CLSID_WICBmpEncoder, params);
4146 }
4147
4148 static GpStatus encode_image_tiff(GpImage *image, IStream* stream,
4149     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4150 {
4151     return encode_image_WIC(image, stream, &CLSID_WICTiffEncoder, params);
4152 }
4153
4154 static GpStatus encode_image_png(GpImage *image, IStream* stream,
4155     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4156 {
4157     return encode_image_WIC(image, stream, &CLSID_WICPngEncoder, params);
4158 }
4159
4160 static GpStatus encode_image_jpeg(GpImage *image, IStream* stream,
4161     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4162 {
4163     return encode_image_WIC(image, stream, &CLSID_WICJpegEncoder, params);
4164 }
4165
4166 /*****************************************************************************
4167  * GdipSaveImageToStream [GDIPLUS.@]
4168  */
4169 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
4170     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4171 {
4172     GpStatus stat;
4173     encode_image_func encode_image;
4174     int i;
4175
4176     TRACE("%p %p %p %p\n", image, stream, clsid, params);
4177
4178     if(!image || !stream)
4179         return InvalidParameter;
4180
4181     /* select correct encoder */
4182     encode_image = NULL;
4183     for (i = 0; i < NUM_CODECS; i++) {
4184         if ((codecs[i].info.Flags & ImageCodecFlagsEncoder) &&
4185             IsEqualCLSID(clsid, &codecs[i].info.Clsid))
4186             encode_image = codecs[i].encode_func;
4187     }
4188     if (encode_image == NULL)
4189         return UnknownImageFormat;
4190
4191     stat = encode_image(image, stream, clsid, params);
4192
4193     return stat;
4194 }
4195
4196 /*****************************************************************************
4197  * GdipSaveAdd [GDIPLUS.@]
4198  */
4199 GpStatus WINGDIPAPI GdipSaveAdd(GpImage *image, GDIPCONST EncoderParameters *params)
4200 {
4201     FIXME("(%p,%p): stub\n", image, params);
4202     return Ok;
4203 }
4204
4205 /*****************************************************************************
4206  * GdipGetImagePalette [GDIPLUS.@]
4207  */
4208 GpStatus WINGDIPAPI GdipGetImagePalette(GpImage *image, ColorPalette *palette, INT size)
4209 {
4210     INT count;
4211
4212     TRACE("(%p,%p,%i)\n", image, palette, size);
4213
4214     if (!image || !palette)
4215         return InvalidParameter;
4216
4217     count = image->palette ? image->palette->Count : 0;
4218
4219     if (size < (sizeof(UINT)*2+sizeof(ARGB)*count))
4220     {
4221         TRACE("<-- InsufficientBuffer\n");
4222         return InsufficientBuffer;
4223     }
4224
4225     if (image->palette)
4226     {
4227         palette->Flags = image->palette->Flags;
4228         palette->Count = image->palette->Count;
4229         memcpy(palette->Entries, image->palette->Entries, sizeof(ARGB)*image->palette->Count);
4230     }
4231     else
4232     {
4233         palette->Flags = 0;
4234         palette->Count = 0;
4235     }
4236     return Ok;
4237 }
4238
4239 /*****************************************************************************
4240  * GdipSetImagePalette [GDIPLUS.@]
4241  */
4242 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
4243     GDIPCONST ColorPalette *palette)
4244 {
4245     ColorPalette *new_palette;
4246
4247     TRACE("(%p,%p)\n", image, palette);
4248
4249     if(!image || !palette || palette->Count > 256)
4250         return InvalidParameter;
4251
4252     new_palette = GdipAlloc(2 * sizeof(UINT) + palette->Count * sizeof(ARGB));
4253     if (!new_palette) return OutOfMemory;
4254
4255     GdipFree(image->palette);
4256     image->palette = new_palette;
4257     image->palette->Flags = palette->Flags;
4258     image->palette->Count = palette->Count;
4259     memcpy(image->palette->Entries, palette->Entries, sizeof(ARGB)*palette->Count);
4260
4261     return Ok;
4262 }
4263
4264 /*************************************************************************
4265  * Encoders -
4266  *   Structures that represent which formats we support for encoding.
4267  */
4268
4269 /* ImageCodecInfo creation routines taken from libgdiplus */
4270 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
4271 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
4272 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
4273 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
4274 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
4275 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
4276
4277 static const WCHAR jpeg_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'J','P','E','G', 0};
4278 static const WCHAR jpeg_extension[] = {'*','.','J','P','G',';', '*','.','J','P','E','G',';', '*','.','J','P','E',';', '*','.','J','F','I','F',0};
4279 static const WCHAR jpeg_mimetype[] = {'i','m','a','g','e','/','j','p','e','g', 0};
4280 static const WCHAR jpeg_format[] = {'J','P','E','G',0};
4281 static const BYTE jpeg_sig_pattern[] = { 0xFF, 0xD8 };
4282 static const BYTE jpeg_sig_mask[] = { 0xFF, 0xFF };
4283
4284 static const WCHAR gif_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'G','I','F', 0};
4285 static const WCHAR gif_extension[] = {'*','.','G','I','F',0};
4286 static const WCHAR gif_mimetype[] = {'i','m','a','g','e','/','g','i','f', 0};
4287 static const WCHAR gif_format[] = {'G','I','F',0};
4288 static const BYTE gif_sig_pattern[12] = "GIF87aGIF89a";
4289 static const BYTE gif_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4290
4291 static const WCHAR tiff_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'T','I','F','F', 0};
4292 static const WCHAR tiff_extension[] = {'*','.','T','I','F','F',';','*','.','T','I','F',0};
4293 static const WCHAR tiff_mimetype[] = {'i','m','a','g','e','/','t','i','f','f', 0};
4294 static const WCHAR tiff_format[] = {'T','I','F','F',0};
4295 static const BYTE tiff_sig_pattern[] = {0x49,0x49,42,0,0x4d,0x4d,0,42};
4296 static const BYTE tiff_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4297
4298 static const WCHAR emf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'E','M','F', 0};
4299 static const WCHAR emf_extension[] = {'*','.','E','M','F',0};
4300 static const WCHAR emf_mimetype[] = {'i','m','a','g','e','/','x','-','e','m','f', 0};
4301 static const WCHAR emf_format[] = {'E','M','F',0};
4302 static const BYTE emf_sig_pattern[] = { 0x01, 0x00, 0x00, 0x00 };
4303 static const BYTE emf_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4304
4305 static const WCHAR wmf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'W','M','F', 0};
4306 static const WCHAR wmf_extension[] = {'*','.','W','M','F',0};
4307 static const WCHAR wmf_mimetype[] = {'i','m','a','g','e','/','x','-','w','m','f', 0};
4308 static const WCHAR wmf_format[] = {'W','M','F',0};
4309 static const BYTE wmf_sig_pattern[] = { 0xd7, 0xcd };
4310 static const BYTE wmf_sig_mask[] = { 0xFF, 0xFF };
4311
4312 static const WCHAR png_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'P','N','G', 0};
4313 static const WCHAR png_extension[] = {'*','.','P','N','G',0};
4314 static const WCHAR png_mimetype[] = {'i','m','a','g','e','/','p','n','g', 0};
4315 static const WCHAR png_format[] = {'P','N','G',0};
4316 static const BYTE png_sig_pattern[] = { 137, 80, 78, 71, 13, 10, 26, 10, };
4317 static const BYTE png_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4318
4319 static const WCHAR ico_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'I','C','O', 0};
4320 static const WCHAR ico_extension[] = {'*','.','I','C','O',0};
4321 static const WCHAR ico_mimetype[] = {'i','m','a','g','e','/','x','-','i','c','o','n', 0};
4322 static const WCHAR ico_format[] = {'I','C','O',0};
4323 static const BYTE ico_sig_pattern[] = { 0x00, 0x00, 0x01, 0x00 };
4324 static const BYTE ico_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4325
4326 static const struct image_codec codecs[NUM_CODECS] = {
4327     {
4328         { /* BMP */
4329             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4330             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4331             /* CodecName */          bmp_codecname,
4332             /* DllName */            NULL,
4333             /* FormatDescription */  bmp_format,
4334             /* FilenameExtension */  bmp_extension,
4335             /* MimeType */           bmp_mimetype,
4336             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4337             /* Version */            1,
4338             /* SigCount */           1,
4339             /* SigSize */            2,
4340             /* SigPattern */         bmp_sig_pattern,
4341             /* SigMask */            bmp_sig_mask,
4342         },
4343         encode_image_BMP,
4344         decode_image_bmp
4345     },
4346     {
4347         { /* JPEG */
4348             /* Clsid */              { 0x557cf401, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4349             /* FormatID */           { 0xb96b3caeU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4350             /* CodecName */          jpeg_codecname,
4351             /* DllName */            NULL,
4352             /* FormatDescription */  jpeg_format,
4353             /* FilenameExtension */  jpeg_extension,
4354             /* MimeType */           jpeg_mimetype,
4355             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4356             /* Version */            1,
4357             /* SigCount */           1,
4358             /* SigSize */            2,
4359             /* SigPattern */         jpeg_sig_pattern,
4360             /* SigMask */            jpeg_sig_mask,
4361         },
4362         encode_image_jpeg,
4363         decode_image_jpeg
4364     },
4365     {
4366         { /* GIF */
4367             /* Clsid */              { 0x557cf402, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4368             /* FormatID */           { 0xb96b3cb0U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4369             /* CodecName */          gif_codecname,
4370             /* DllName */            NULL,
4371             /* FormatDescription */  gif_format,
4372             /* FilenameExtension */  gif_extension,
4373             /* MimeType */           gif_mimetype,
4374             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4375             /* Version */            1,
4376             /* SigCount */           2,
4377             /* SigSize */            6,
4378             /* SigPattern */         gif_sig_pattern,
4379             /* SigMask */            gif_sig_mask,
4380         },
4381         NULL,
4382         decode_image_gif
4383     },
4384     {
4385         { /* TIFF */
4386             /* Clsid */              { 0x557cf405, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4387             /* FormatID */           { 0xb96b3cb1U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4388             /* CodecName */          tiff_codecname,
4389             /* DllName */            NULL,
4390             /* FormatDescription */  tiff_format,
4391             /* FilenameExtension */  tiff_extension,
4392             /* MimeType */           tiff_mimetype,
4393             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsEncoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4394             /* Version */            1,
4395             /* SigCount */           2,
4396             /* SigSize */            4,
4397             /* SigPattern */         tiff_sig_pattern,
4398             /* SigMask */            tiff_sig_mask,
4399         },
4400         encode_image_tiff,
4401         decode_image_tiff
4402     },
4403     {
4404         { /* EMF */
4405             /* Clsid */              { 0x557cf403, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4406             /* FormatID */           { 0xb96b3cacU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4407             /* CodecName */          emf_codecname,
4408             /* DllName */            NULL,
4409             /* FormatDescription */  emf_format,
4410             /* FilenameExtension */  emf_extension,
4411             /* MimeType */           emf_mimetype,
4412             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4413             /* Version */            1,
4414             /* SigCount */           1,
4415             /* SigSize */            4,
4416             /* SigPattern */         emf_sig_pattern,
4417             /* SigMask */            emf_sig_mask,
4418         },
4419         NULL,
4420         decode_image_olepicture_metafile
4421     },
4422     {
4423         { /* WMF */
4424             /* Clsid */              { 0x557cf404, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4425             /* FormatID */           { 0xb96b3cadU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4426             /* CodecName */          wmf_codecname,
4427             /* DllName */            NULL,
4428             /* FormatDescription */  wmf_format,
4429             /* FilenameExtension */  wmf_extension,
4430             /* MimeType */           wmf_mimetype,
4431             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4432             /* Version */            1,
4433             /* SigCount */           1,
4434             /* SigSize */            2,
4435             /* SigPattern */         wmf_sig_pattern,
4436             /* SigMask */            wmf_sig_mask,
4437         },
4438         NULL,
4439         decode_image_olepicture_metafile
4440     },
4441     {
4442         { /* PNG */
4443             /* Clsid */              { 0x557cf406, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4444             /* FormatID */           { 0xb96b3cafU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4445             /* CodecName */          png_codecname,
4446             /* DllName */            NULL,
4447             /* FormatDescription */  png_format,
4448             /* FilenameExtension */  png_extension,
4449             /* MimeType */           png_mimetype,
4450             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4451             /* Version */            1,
4452             /* SigCount */           1,
4453             /* SigSize */            8,
4454             /* SigPattern */         png_sig_pattern,
4455             /* SigMask */            png_sig_mask,
4456         },
4457         encode_image_png,
4458         decode_image_png
4459     },
4460     {
4461         { /* ICO */
4462             /* Clsid */              { 0x557cf407, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4463             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4464             /* CodecName */          ico_codecname,
4465             /* DllName */            NULL,
4466             /* FormatDescription */  ico_format,
4467             /* FilenameExtension */  ico_extension,
4468             /* MimeType */           ico_mimetype,
4469             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4470             /* Version */            1,
4471             /* SigCount */           1,
4472             /* SigSize */            4,
4473             /* SigPattern */         ico_sig_pattern,
4474             /* SigMask */            ico_sig_mask,
4475         },
4476         NULL,
4477         decode_image_icon
4478     },
4479 };
4480
4481 /*****************************************************************************
4482  * GdipGetImageDecodersSize [GDIPLUS.@]
4483  */
4484 GpStatus WINGDIPAPI GdipGetImageDecodersSize(UINT *numDecoders, UINT *size)
4485 {
4486     int decoder_count=0;
4487     int i;
4488     TRACE("%p %p\n", numDecoders, size);
4489
4490     if (!numDecoders || !size)
4491         return InvalidParameter;
4492
4493     for (i=0; i<NUM_CODECS; i++)
4494     {
4495         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4496             decoder_count++;
4497     }
4498
4499     *numDecoders = decoder_count;
4500     *size = decoder_count * sizeof(ImageCodecInfo);
4501
4502     return Ok;
4503 }
4504
4505 /*****************************************************************************
4506  * GdipGetImageDecoders [GDIPLUS.@]
4507  */
4508 GpStatus WINGDIPAPI GdipGetImageDecoders(UINT numDecoders, UINT size, ImageCodecInfo *decoders)
4509 {
4510     int i, decoder_count=0;
4511     TRACE("%u %u %p\n", numDecoders, size, decoders);
4512
4513     if (!decoders ||
4514         size != numDecoders * sizeof(ImageCodecInfo))
4515         return GenericError;
4516
4517     for (i=0; i<NUM_CODECS; i++)
4518     {
4519         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4520         {
4521             if (decoder_count == numDecoders) return GenericError;
4522             memcpy(&decoders[decoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4523             decoder_count++;
4524         }
4525     }
4526
4527     if (decoder_count < numDecoders) return GenericError;
4528
4529     return Ok;
4530 }
4531
4532 /*****************************************************************************
4533  * GdipGetImageEncodersSize [GDIPLUS.@]
4534  */
4535 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
4536 {
4537     int encoder_count=0;
4538     int i;
4539     TRACE("%p %p\n", numEncoders, size);
4540
4541     if (!numEncoders || !size)
4542         return InvalidParameter;
4543
4544     for (i=0; i<NUM_CODECS; i++)
4545     {
4546         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4547             encoder_count++;
4548     }
4549
4550     *numEncoders = encoder_count;
4551     *size = encoder_count * sizeof(ImageCodecInfo);
4552
4553     return Ok;
4554 }
4555
4556 /*****************************************************************************
4557  * GdipGetImageEncoders [GDIPLUS.@]
4558  */
4559 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
4560 {
4561     int i, encoder_count=0;
4562     TRACE("%u %u %p\n", numEncoders, size, encoders);
4563
4564     if (!encoders ||
4565         size != numEncoders * sizeof(ImageCodecInfo))
4566         return GenericError;
4567
4568     for (i=0; i<NUM_CODECS; i++)
4569     {
4570         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4571         {
4572             if (encoder_count == numEncoders) return GenericError;
4573             memcpy(&encoders[encoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4574             encoder_count++;
4575         }
4576     }
4577
4578     if (encoder_count < numEncoders) return GenericError;
4579
4580     return Ok;
4581 }
4582
4583 GpStatus WINGDIPAPI GdipGetEncoderParameterListSize(GpImage *image,
4584     GDIPCONST CLSID* clsidEncoder, UINT *size)
4585 {
4586     static int calls;
4587
4588     TRACE("(%p,%s,%p)\n", image, debugstr_guid(clsidEncoder), size);
4589
4590     if(!(calls++))
4591         FIXME("not implemented\n");
4592
4593     *size = 0;
4594
4595     return NotImplemented;
4596 }
4597
4598 static PixelFormat get_16bpp_format(HBITMAP hbm)
4599 {
4600     BITMAPV4HEADER bmh;
4601     HDC hdc;
4602     PixelFormat result;
4603
4604     hdc = CreateCompatibleDC(NULL);
4605
4606     memset(&bmh, 0, sizeof(bmh));
4607     bmh.bV4Size = sizeof(bmh);
4608     bmh.bV4Width = 1;
4609     bmh.bV4Height = 1;
4610     bmh.bV4V4Compression = BI_BITFIELDS;
4611     bmh.bV4BitCount = 16;
4612
4613     GetDIBits(hdc, hbm, 0, 0, NULL, (BITMAPINFO*)&bmh, DIB_RGB_COLORS);
4614
4615     if (bmh.bV4RedMask == 0x7c00 &&
4616         bmh.bV4GreenMask == 0x3e0 &&
4617         bmh.bV4BlueMask == 0x1f)
4618     {
4619         result = PixelFormat16bppRGB555;
4620     }
4621     else if (bmh.bV4RedMask == 0xf800 &&
4622         bmh.bV4GreenMask == 0x7e0 &&
4623         bmh.bV4BlueMask == 0x1f)
4624     {
4625         result = PixelFormat16bppRGB565;
4626     }
4627     else
4628     {
4629         FIXME("unrecognized bitfields %x,%x,%x\n", bmh.bV4RedMask,
4630             bmh.bV4GreenMask, bmh.bV4BlueMask);
4631         result = PixelFormatUndefined;
4632     }
4633
4634     DeleteDC(hdc);
4635
4636     return result;
4637 }
4638
4639 /*****************************************************************************
4640  * GdipCreateBitmapFromHBITMAP [GDIPLUS.@]
4641  */
4642 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
4643 {
4644     BITMAP bm;
4645     GpStatus retval;
4646     PixelFormat format;
4647     BitmapData lockeddata;
4648     INT y;
4649
4650     TRACE("%p %p %p\n", hbm, hpal, bitmap);
4651
4652     if(!hbm || !bitmap)
4653         return InvalidParameter;
4654
4655     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
4656             return InvalidParameter;
4657
4658     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
4659     switch(bm.bmBitsPixel) {
4660         case 1:
4661             format = PixelFormat1bppIndexed;
4662             break;
4663         case 4:
4664             format = PixelFormat4bppIndexed;
4665             break;
4666         case 8:
4667             format = PixelFormat8bppIndexed;
4668             break;
4669         case 16:
4670             format = get_16bpp_format(hbm);
4671             if (format == PixelFormatUndefined)
4672                 return InvalidParameter;
4673             break;
4674         case 24:
4675             format = PixelFormat24bppRGB;
4676             break;
4677         case 32:
4678             format = PixelFormat32bppRGB;
4679             break;
4680         case 48:
4681             format = PixelFormat48bppRGB;
4682             break;
4683         default:
4684             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
4685             return InvalidParameter;
4686     }
4687
4688     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, 0,
4689         format, NULL, bitmap);
4690
4691     if (retval == Ok)
4692     {
4693         retval = GdipBitmapLockBits(*bitmap, NULL, ImageLockModeWrite,
4694             format, &lockeddata);
4695         if (retval == Ok)
4696         {
4697             if (bm.bmBits)
4698             {
4699                 for (y=0; y<bm.bmHeight; y++)
4700                 {
4701                     memcpy((BYTE*)lockeddata.Scan0+lockeddata.Stride*y,
4702                            (BYTE*)bm.bmBits+bm.bmWidthBytes*(bm.bmHeight-1-y),
4703                            bm.bmWidthBytes);
4704                 }
4705             }
4706             else
4707             {
4708                 HDC hdc;
4709                 HBITMAP oldhbm;
4710                 BITMAPINFO *pbmi;
4711                 INT src_height, dst_stride;
4712                 BYTE *dst_bits;
4713
4714                 hdc = CreateCompatibleDC(NULL);
4715                 oldhbm = SelectObject(hdc, hbm);
4716
4717                 pbmi = GdipAlloc(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD));
4718
4719                 if (pbmi)
4720                 {
4721                     pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
4722                     pbmi->bmiHeader.biBitCount = 0;
4723
4724                     GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
4725
4726                     src_height = abs(pbmi->bmiHeader.biHeight);
4727
4728                     if (pbmi->bmiHeader.biHeight > 0)
4729                     {
4730                         dst_bits = (BYTE*)lockeddata.Scan0+lockeddata.Stride*(src_height-1);
4731                         dst_stride = -lockeddata.Stride;
4732                     }
4733                     else
4734                     {
4735                         dst_bits = lockeddata.Scan0;
4736                         dst_stride = lockeddata.Stride;
4737                     }
4738
4739                     for (y=0; y<src_height; y++)
4740                     {
4741                         GetDIBits(hdc, hbm, y, 1, dst_bits+dst_stride*y,
4742                             pbmi, DIB_RGB_COLORS);
4743                     }
4744
4745                     GdipFree(pbmi);
4746                 }
4747                 else
4748                     retval = OutOfMemory;
4749
4750                 SelectObject(hdc, oldhbm);
4751                 DeleteDC(hdc);
4752             }
4753
4754             GdipBitmapUnlockBits(*bitmap, &lockeddata);
4755         }
4756
4757         if (retval == Ok && hpal)
4758         {
4759             WORD num_palette_entries;
4760             PALETTEENTRY *palette_entries=NULL;
4761             ColorPalette *palette=NULL;
4762             int i;
4763
4764             if (!GetObjectW(hpal, sizeof(num_palette_entries), &num_palette_entries))
4765                 retval = GenericError;
4766
4767             if (retval == Ok)
4768             {
4769                 palette_entries = GdipAlloc(sizeof(PALETTEENTRY) * num_palette_entries);
4770                 palette = GdipAlloc(sizeof(ColorPalette) + sizeof(ARGB) * (num_palette_entries-1));
4771
4772                 if (!palette_entries || !palette)
4773                     retval = OutOfMemory;
4774             }
4775
4776             if (retval == Ok)
4777             {
4778                 if (!GetPaletteEntries(hpal, 0, num_palette_entries, palette_entries))
4779                     retval = GenericError;
4780             }
4781
4782             if (retval == Ok)
4783             {
4784                 palette->Flags = 0;
4785                 palette->Count = num_palette_entries;
4786
4787                 for (i=0; i<num_palette_entries; i++)
4788                 {
4789                     PALETTEENTRY * entry = &palette_entries[i];
4790                     palette->Entries[i] = 0xff000000 | entry->peRed << 16 |
4791                         entry->peGreen << 8 | entry->peBlue;
4792                 }
4793
4794                 retval = GdipSetImagePalette((GpImage*)*bitmap, palette);
4795             }
4796
4797             GdipFree(palette_entries);
4798             GdipFree(palette);
4799         }
4800
4801         if (retval != Ok)
4802         {
4803             GdipDisposeImage((GpImage*)*bitmap);
4804             *bitmap = NULL;
4805         }
4806     }
4807
4808     return retval;
4809 }
4810
4811 GpStatus WINGDIPAPI GdipDeleteEffect(CGpEffect *effect)
4812 {
4813     FIXME("(%p): stub\n", effect);
4814     /* note: According to Jose Roca's GDI+ Docs, this is not implemented
4815      * in Windows's gdiplus */
4816     return NotImplemented;
4817 }
4818
4819 /*****************************************************************************
4820  * GdipSetEffectParameters [GDIPLUS.@]
4821  */
4822 GpStatus WINGDIPAPI GdipSetEffectParameters(CGpEffect *effect,
4823     const VOID *params, const UINT size)
4824 {
4825     static int calls;
4826
4827     TRACE("(%p,%p,%u)\n", effect, params, size);
4828
4829     if(!(calls++))
4830         FIXME("not implemented\n");
4831
4832     return NotImplemented;
4833 }
4834
4835 /*****************************************************************************
4836  * GdipGetImageFlags [GDIPLUS.@]
4837  */
4838 GpStatus WINGDIPAPI GdipGetImageFlags(GpImage *image, UINT *flags)
4839 {
4840     TRACE("%p %p\n", image, flags);
4841
4842     if(!image || !flags)
4843         return InvalidParameter;
4844
4845     *flags = image->flags;
4846
4847     return Ok;
4848 }
4849
4850 GpStatus WINGDIPAPI GdipTestControl(GpTestControlEnum control, void *param)
4851 {
4852     TRACE("(%d, %p)\n", control, param);
4853
4854     switch(control){
4855         case TestControlForceBilinear:
4856             if(param)
4857                 FIXME("TestControlForceBilinear not handled\n");
4858             break;
4859         case TestControlNoICM:
4860             if(param)
4861                 FIXME("TestControlNoICM not handled\n");
4862             break;
4863         case TestControlGetBuildNumber:
4864             *((DWORD*)param) = 3102;
4865             break;
4866     }
4867
4868     return Ok;
4869 }
4870
4871 GpStatus WINGDIPAPI GdipRecordMetafileFileName(GDIPCONST WCHAR* fileName,
4872                             HDC hdc, EmfType type, GDIPCONST GpRectF *pFrameRect,
4873                             MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc,
4874                             GpMetafile **metafile)
4875 {
4876     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4877                                  frameUnit, debugstr_w(desc), metafile);
4878
4879     return NotImplemented;
4880 }
4881
4882 GpStatus WINGDIPAPI GdipRecordMetafileFileNameI(GDIPCONST WCHAR* fileName, HDC hdc, EmfType type,
4883                             GDIPCONST GpRect *pFrameRect, MetafileFrameUnit frameUnit,
4884                             GDIPCONST WCHAR *desc, GpMetafile **metafile)
4885 {
4886     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4887                                  frameUnit, debugstr_w(desc), metafile);
4888
4889     return NotImplemented;
4890 }
4891
4892 GpStatus WINGDIPAPI GdipImageForceValidation(GpImage *image)
4893 {
4894     TRACE("%p\n", image);
4895
4896     return Ok;
4897 }
4898
4899 /*****************************************************************************
4900  * GdipGetImageThumbnail [GDIPLUS.@]
4901  */
4902 GpStatus WINGDIPAPI GdipGetImageThumbnail(GpImage *image, UINT width, UINT height,
4903                             GpImage **ret_image, GetThumbnailImageAbort cb,
4904                             VOID * cb_data)
4905 {
4906     GpStatus stat;
4907     GpGraphics *graphics;
4908     UINT srcwidth, srcheight;
4909
4910     TRACE("(%p %u %u %p %p %p)\n",
4911         image, width, height, ret_image, cb, cb_data);
4912
4913     if (!image || !ret_image)
4914         return InvalidParameter;
4915
4916     if (!width) width = 120;
4917     if (!height) height = 120;
4918
4919     GdipGetImageWidth(image, &srcwidth);
4920     GdipGetImageHeight(image, &srcheight);
4921
4922     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppPARGB,
4923         NULL, (GpBitmap**)ret_image);
4924
4925     if (stat == Ok)
4926     {
4927         stat = GdipGetImageGraphicsContext(*ret_image, &graphics);
4928
4929         if (stat == Ok)
4930         {
4931             stat = GdipDrawImageRectRectI(graphics, image,
4932                 0, 0, width, height, 0, 0, srcwidth, srcheight, UnitPixel,
4933                 NULL, NULL, NULL);
4934
4935             GdipDeleteGraphics(graphics);
4936         }
4937
4938         if (stat != Ok)
4939         {
4940             GdipDisposeImage(*ret_image);
4941             *ret_image = NULL;
4942         }
4943     }
4944
4945     return stat;
4946 }
4947
4948 /*****************************************************************************
4949  * GdipImageRotateFlip [GDIPLUS.@]
4950  */
4951 GpStatus WINGDIPAPI GdipImageRotateFlip(GpImage *image, RotateFlipType type)
4952 {
4953     GpBitmap *new_bitmap;
4954     GpBitmap *bitmap;
4955     int bpp, bytesperpixel;
4956     int rotate_90, flip_x, flip_y;
4957     int src_x_offset, src_y_offset;
4958     LPBYTE src_origin;
4959     UINT x, y, width, height;
4960     BitmapData src_lock, dst_lock;
4961     GpStatus stat;
4962
4963     TRACE("(%p, %u)\n", image, type);
4964
4965     if (!image)
4966         return InvalidParameter;
4967
4968     rotate_90 = type&1;
4969     flip_x = (type&6) == 2 || (type&6) == 4;
4970     flip_y = (type&3) == 1 || (type&3) == 2;
4971
4972     if (image->type != ImageTypeBitmap)
4973     {
4974         FIXME("Not implemented for type %i\n", image->type);
4975         return NotImplemented;
4976     }
4977
4978     bitmap = (GpBitmap*)image;
4979     bpp = PIXELFORMATBPP(bitmap->format);
4980
4981     if (bpp < 8)
4982     {
4983         FIXME("Not implemented for %i bit images\n", bpp);
4984         return NotImplemented;
4985     }
4986
4987     if (rotate_90)
4988     {
4989         width = bitmap->height;
4990         height = bitmap->width;
4991     }
4992     else
4993     {
4994         width = bitmap->width;
4995         height = bitmap->height;
4996     }
4997
4998     bytesperpixel = bpp/8;
4999
5000     stat = GdipCreateBitmapFromScan0(width, height, 0, bitmap->format, NULL, &new_bitmap);
5001
5002     if (stat != Ok)
5003         return stat;
5004
5005     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format, &src_lock);
5006
5007     if (stat == Ok)
5008     {
5009         stat = GdipBitmapLockBits(new_bitmap, NULL, ImageLockModeWrite, bitmap->format, &dst_lock);
5010
5011         if (stat == Ok)
5012         {
5013             LPBYTE src_row, src_pixel;
5014             LPBYTE dst_row, dst_pixel;
5015
5016             src_origin = src_lock.Scan0;
5017             if (flip_x) src_origin += bytesperpixel * (bitmap->width - 1);
5018             if (flip_y) src_origin += src_lock.Stride * (bitmap->height - 1);
5019
5020             if (rotate_90)
5021             {
5022                 if (flip_y) src_x_offset = -src_lock.Stride;
5023                 else src_x_offset = src_lock.Stride;
5024                 if (flip_x) src_y_offset = -bytesperpixel;
5025                 else src_y_offset = bytesperpixel;
5026             }
5027             else
5028             {
5029                 if (flip_x) src_x_offset = -bytesperpixel;
5030                 else src_x_offset = bytesperpixel;
5031                 if (flip_y) src_y_offset = -src_lock.Stride;
5032                 else src_y_offset = src_lock.Stride;
5033             }
5034
5035             src_row = src_origin;
5036             dst_row = dst_lock.Scan0;
5037             for (y=0; y<height; y++)
5038             {
5039                 src_pixel = src_row;
5040                 dst_pixel = dst_row;
5041                 for (x=0; x<width; x++)
5042                 {
5043                     /* FIXME: This could probably be faster without memcpy. */
5044                     memcpy(dst_pixel, src_pixel, bytesperpixel);
5045                     dst_pixel += bytesperpixel;
5046                     src_pixel += src_x_offset;
5047                 }
5048                 src_row += src_y_offset;
5049                 dst_row += dst_lock.Stride;
5050             }
5051
5052             GdipBitmapUnlockBits(new_bitmap, &dst_lock);
5053         }
5054
5055         GdipBitmapUnlockBits(bitmap, &src_lock);
5056     }
5057
5058     if (stat == Ok)
5059         move_bitmap(bitmap, new_bitmap, FALSE);
5060     else
5061         GdipDisposeImage((GpImage*)new_bitmap);
5062
5063     return stat;
5064 }
5065
5066 /*****************************************************************************
5067  * GdipConvertToEmfPlusToFile [GDIPLUS.@]
5068  */
5069
5070 GpStatus WINGDIPAPI GdipConvertToEmfPlusToFile(const GpGraphics* refGraphics,
5071                                                GpMetafile* metafile, BOOL* conversionSuccess,
5072                                                const WCHAR* filename, EmfType emfType,
5073                                                const WCHAR* description, GpMetafile** out_metafile)
5074 {
5075     FIXME("stub: %p, %p, %p, %p, %u, %p, %p\n", refGraphics, metafile, conversionSuccess, filename, emfType, description, out_metafile);
5076     return NotImplemented;
5077 }