jscript: Rename jsheap_t to heap_pool_t.
[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     UINT 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, stride;
1632     GpRect rect;
1633     BitmapData lockeddata;
1634     HDC screendc;
1635     BOOL has_alpha;
1636     int x, y;
1637     BITMAPINFOHEADER bih;
1638     DWORD *src;
1639     BYTE *dst_row;
1640     DWORD *dst;
1641
1642     TRACE("%p, %p\n", hicon, bitmap);
1643
1644     if(!bitmap || !GetIconInfo(hicon, &iinfo))
1645         return InvalidParameter;
1646
1647     /* get the size of the icon */
1648     ret = GetObjectA(iinfo.hbmColor ? iinfo.hbmColor : iinfo.hbmMask, sizeof(bm), &bm);
1649     if (ret == 0) {
1650         DeleteObject(iinfo.hbmColor);
1651         DeleteObject(iinfo.hbmMask);
1652         return GenericError;
1653     }
1654
1655     width = bm.bmWidth;
1656     height = iinfo.hbmColor ? abs(bm.bmHeight) : abs(bm.bmHeight) / 2;
1657     stride = width * 4;
1658
1659     stat = GdipCreateBitmapFromScan0(width, height, stride, PixelFormat32bppARGB, NULL, bitmap);
1660     if (stat != Ok) {
1661         DeleteObject(iinfo.hbmColor);
1662         DeleteObject(iinfo.hbmMask);
1663         return stat;
1664     }
1665
1666     rect.X = 0;
1667     rect.Y = 0;
1668     rect.Width = width;
1669     rect.Height = height;
1670
1671     stat = GdipBitmapLockBits(*bitmap, &rect, ImageLockModeWrite, PixelFormat32bppARGB, &lockeddata);
1672     if (stat != Ok) {
1673         DeleteObject(iinfo.hbmColor);
1674         DeleteObject(iinfo.hbmMask);
1675         GdipDisposeImage((GpImage*)*bitmap);
1676         return stat;
1677     }
1678
1679     bih.biSize = sizeof(bih);
1680     bih.biWidth = width;
1681     bih.biHeight = iinfo.hbmColor ? -height: -height * 2;
1682     bih.biPlanes = 1;
1683     bih.biBitCount = 32;
1684     bih.biCompression = BI_RGB;
1685     bih.biSizeImage = 0;
1686     bih.biXPelsPerMeter = 0;
1687     bih.biYPelsPerMeter = 0;
1688     bih.biClrUsed = 0;
1689     bih.biClrImportant = 0;
1690
1691     screendc = GetDC(0);
1692     if (iinfo.hbmColor)
1693     {
1694         GetDIBits(screendc, iinfo.hbmColor, 0, height, lockeddata.Scan0, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1695
1696         if (bm.bmBitsPixel == 32)
1697         {
1698             has_alpha = FALSE;
1699
1700             /* If any pixel has a non-zero alpha, ignore hbmMask */
1701             src = (DWORD*)lockeddata.Scan0;
1702             for (x=0; x<width && !has_alpha; x++)
1703                 for (y=0; y<height && !has_alpha; y++)
1704                     if ((*src++ & 0xff000000) != 0)
1705                         has_alpha = TRUE;
1706         }
1707         else has_alpha = FALSE;
1708     }
1709     else
1710     {
1711         GetDIBits(screendc, iinfo.hbmMask, 0, height, lockeddata.Scan0, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1712         has_alpha = FALSE;
1713     }
1714
1715     if (!has_alpha)
1716     {
1717         if (iinfo.hbmMask)
1718         {
1719             BYTE *bits = HeapAlloc(GetProcessHeap(), 0, height * stride);
1720
1721             /* read alpha data from the mask */
1722             if (iinfo.hbmColor)
1723                 GetDIBits(screendc, iinfo.hbmMask, 0, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1724             else
1725                 GetDIBits(screendc, iinfo.hbmMask, height, height, bits, (BITMAPINFO*)&bih, DIB_RGB_COLORS);
1726
1727             src = (DWORD*)bits;
1728             dst_row = lockeddata.Scan0;
1729             for (y=0; y<height; y++)
1730             {
1731                 dst = (DWORD*)dst_row;
1732                 for (x=0; x<height; x++)
1733                 {
1734                     DWORD src_value = *src++;
1735                     if (src_value)
1736                         *dst++ = 0;
1737                     else
1738                         *dst++ |= 0xff000000;
1739                 }
1740                 dst_row += lockeddata.Stride;
1741             }
1742
1743             HeapFree(GetProcessHeap(), 0, bits);
1744         }
1745         else
1746         {
1747             /* set constant alpha of 255 */
1748             dst_row = lockeddata.Scan0;
1749             for (y=0; y<height; y++)
1750             {
1751                 dst = (DWORD*)dst_row;
1752                 for (x=0; x<height; x++)
1753                     *dst++ |= 0xff000000;
1754                 dst_row += lockeddata.Stride;
1755             }
1756         }
1757     }
1758
1759     ReleaseDC(0, screendc);
1760
1761     DeleteObject(iinfo.hbmColor);
1762     DeleteObject(iinfo.hbmMask);
1763
1764     GdipBitmapUnlockBits(*bitmap, &lockeddata);
1765
1766     return Ok;
1767 }
1768
1769 static void generate_halftone_palette(ARGB *entries, UINT count)
1770 {
1771     static const BYTE halftone_values[6]={0x00,0x33,0x66,0x99,0xcc,0xff};
1772     UINT i;
1773
1774     for (i=0; i<8 && i<count; i++)
1775     {
1776         entries[i] = 0xff000000;
1777         if (i&1) entries[i] |= 0x800000;
1778         if (i&2) entries[i] |= 0x8000;
1779         if (i&4) entries[i] |= 0x80;
1780     }
1781
1782     if (8 < count)
1783         entries[i] = 0xffc0c0c0;
1784
1785     for (i=9; i<16 && i<count; i++)
1786     {
1787         entries[i] = 0xff000000;
1788         if (i&1) entries[i] |= 0xff0000;
1789         if (i&2) entries[i] |= 0xff00;
1790         if (i&4) entries[i] |= 0xff;
1791     }
1792
1793     for (i=16; i<40 && i<count; i++)
1794     {
1795         entries[i] = 0;
1796     }
1797
1798     for (i=40; i<256 && i<count; i++)
1799     {
1800         entries[i] = 0xff000000;
1801         entries[i] |= halftone_values[(i-40)%6];
1802         entries[i] |= halftone_values[((i-40)/6)%6] << 8;
1803         entries[i] |= halftone_values[((i-40)/36)%6] << 16;
1804     }
1805 }
1806
1807 static GpStatus get_screen_resolution(REAL *xres, REAL *yres)
1808 {
1809     HDC screendc = GetDC(0);
1810
1811     if (!screendc) return GenericError;
1812
1813     *xres = (REAL)GetDeviceCaps(screendc, LOGPIXELSX);
1814     *yres = (REAL)GetDeviceCaps(screendc, LOGPIXELSY);
1815
1816     ReleaseDC(0, screendc);
1817
1818     return Ok;
1819 }
1820
1821 GpStatus WINGDIPAPI GdipCreateBitmapFromScan0(INT width, INT height, INT stride,
1822     PixelFormat format, BYTE* scan0, GpBitmap** bitmap)
1823 {
1824     HBITMAP hbitmap=NULL;
1825     INT row_size, dib_stride;
1826     BYTE *bits=NULL, *own_bits=NULL;
1827     REAL xres, yres;
1828     GpStatus stat;
1829
1830     TRACE("%d %d %d 0x%x %p %p\n", width, height, stride, format, scan0, bitmap);
1831
1832     if (!bitmap) return InvalidParameter;
1833
1834     if(width <= 0 || height <= 0 || (scan0 && (stride % 4))){
1835         *bitmap = NULL;
1836         return InvalidParameter;
1837     }
1838
1839     if(scan0 && !stride)
1840         return InvalidParameter;
1841
1842     stat = get_screen_resolution(&xres, &yres);
1843     if (stat != Ok) return stat;
1844
1845     row_size = (width * PIXELFORMATBPP(format)+7) / 8;
1846     dib_stride = (row_size + 3) & ~3;
1847
1848     if(stride == 0)
1849         stride = dib_stride;
1850
1851     if (format & PixelFormatGDI && !(format & (PixelFormatAlpha|PixelFormatIndexed)) && !scan0)
1852     {
1853         char bmibuf[FIELD_OFFSET(BITMAPINFO, bmiColors[256])];
1854         BITMAPINFO *pbmi = (BITMAPINFO *)bmibuf;
1855
1856         pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1857         pbmi->bmiHeader.biWidth = width;
1858         pbmi->bmiHeader.biHeight = -height;
1859         pbmi->bmiHeader.biPlanes = 1;
1860         /* FIXME: use the rest of the data from format */
1861         pbmi->bmiHeader.biBitCount = PIXELFORMATBPP(format);
1862         pbmi->bmiHeader.biCompression = BI_RGB;
1863         pbmi->bmiHeader.biSizeImage = 0;
1864         pbmi->bmiHeader.biXPelsPerMeter = 0;
1865         pbmi->bmiHeader.biYPelsPerMeter = 0;
1866         pbmi->bmiHeader.biClrUsed = 0;
1867         pbmi->bmiHeader.biClrImportant = 0;
1868
1869         hbitmap = CreateDIBSection(0, pbmi, DIB_RGB_COLORS, (void**)&bits, NULL, 0);
1870
1871         if (!hbitmap) return GenericError;
1872
1873         stride = dib_stride;
1874     }
1875     else
1876     {
1877         /* Not a GDI format; don't try to make an HBITMAP. */
1878         if (scan0)
1879             bits = scan0;
1880         else
1881         {
1882             INT size = abs(stride) * height;
1883
1884             own_bits = bits = GdipAlloc(size);
1885             if (!own_bits) return OutOfMemory;
1886
1887             if (stride < 0)
1888                 bits += stride * (1 - height);
1889         }
1890     }
1891
1892     *bitmap = GdipAlloc(sizeof(GpBitmap));
1893     if(!*bitmap)
1894     {
1895         DeleteObject(hbitmap);
1896         GdipFree(own_bits);
1897         return OutOfMemory;
1898     }
1899
1900     (*bitmap)->image.type = ImageTypeBitmap;
1901     memcpy(&(*bitmap)->image.format, &ImageFormatMemoryBMP, sizeof(GUID));
1902     (*bitmap)->image.flags = ImageFlagsNone;
1903     (*bitmap)->image.frame_count = 1;
1904     (*bitmap)->image.current_frame = 0;
1905     (*bitmap)->image.palette = NULL;
1906     (*bitmap)->image.xres = xres;
1907     (*bitmap)->image.yres = yres;
1908     (*bitmap)->width = width;
1909     (*bitmap)->height = height;
1910     (*bitmap)->format = format;
1911     (*bitmap)->image.picture = NULL;
1912     (*bitmap)->image.stream = NULL;
1913     (*bitmap)->hbitmap = hbitmap;
1914     (*bitmap)->hdc = NULL;
1915     (*bitmap)->bits = bits;
1916     (*bitmap)->stride = stride;
1917     (*bitmap)->own_bits = own_bits;
1918     (*bitmap)->metadata_reader = NULL;
1919     (*bitmap)->prop_count = 0;
1920     (*bitmap)->prop_item = NULL;
1921
1922     /* set format-related flags */
1923     if (format & (PixelFormatAlpha|PixelFormatPAlpha|PixelFormatIndexed))
1924         (*bitmap)->image.flags |= ImageFlagsHasAlpha;
1925
1926     if (format == PixelFormat1bppIndexed ||
1927         format == PixelFormat4bppIndexed ||
1928         format == PixelFormat8bppIndexed)
1929     {
1930         (*bitmap)->image.palette = GdipAlloc(sizeof(UINT) * 2 + sizeof(ARGB) * (1 << PIXELFORMATBPP(format)));
1931
1932         if (!(*bitmap)->image.palette)
1933         {
1934             GdipDisposeImage(&(*bitmap)->image);
1935             *bitmap = NULL;
1936             return OutOfMemory;
1937         }
1938
1939         (*bitmap)->image.palette->Count = 1 << PIXELFORMATBPP(format);
1940
1941         if (format == PixelFormat1bppIndexed)
1942         {
1943             (*bitmap)->image.palette->Flags = PaletteFlagsGrayScale;
1944             (*bitmap)->image.palette->Entries[0] = 0xff000000;
1945             (*bitmap)->image.palette->Entries[1] = 0xffffffff;
1946         }
1947         else
1948         {
1949             if (format == PixelFormat8bppIndexed)
1950                 (*bitmap)->image.palette->Flags = PaletteFlagsHalftone;
1951
1952             generate_halftone_palette((*bitmap)->image.palette->Entries,
1953                 (*bitmap)->image.palette->Count);
1954         }
1955     }
1956
1957     TRACE("<-- %p\n", *bitmap);
1958
1959     return Ok;
1960 }
1961
1962 GpStatus WINGDIPAPI GdipCreateBitmapFromStream(IStream* stream,
1963     GpBitmap **bitmap)
1964 {
1965     GpStatus stat;
1966
1967     TRACE("%p %p\n", stream, bitmap);
1968
1969     stat = GdipLoadImageFromStream(stream, (GpImage**) bitmap);
1970
1971     if(stat != Ok)
1972         return stat;
1973
1974     if((*bitmap)->image.type != ImageTypeBitmap){
1975         GdipDisposeImage(&(*bitmap)->image);
1976         *bitmap = NULL;
1977         return GenericError; /* FIXME: what error to return? */
1978     }
1979
1980     return Ok;
1981 }
1982
1983 /* FIXME: no icm */
1984 GpStatus WINGDIPAPI GdipCreateBitmapFromStreamICM(IStream* stream,
1985     GpBitmap **bitmap)
1986 {
1987     TRACE("%p %p\n", stream, bitmap);
1988
1989     return GdipCreateBitmapFromStream(stream, bitmap);
1990 }
1991
1992 GpStatus WINGDIPAPI GdipCreateCachedBitmap(GpBitmap *bitmap, GpGraphics *graphics,
1993     GpCachedBitmap **cachedbmp)
1994 {
1995     GpStatus stat;
1996
1997     TRACE("%p %p %p\n", bitmap, graphics, cachedbmp);
1998
1999     if(!bitmap || !graphics || !cachedbmp)
2000         return InvalidParameter;
2001
2002     *cachedbmp = GdipAlloc(sizeof(GpCachedBitmap));
2003     if(!*cachedbmp)
2004         return OutOfMemory;
2005
2006     stat = GdipCloneImage(&(bitmap->image), &(*cachedbmp)->image);
2007     if(stat != Ok){
2008         GdipFree(*cachedbmp);
2009         return stat;
2010     }
2011
2012     return Ok;
2013 }
2014
2015 GpStatus WINGDIPAPI GdipCreateHICONFromBitmap(GpBitmap *bitmap, HICON *hicon)
2016 {
2017     GpStatus stat;
2018     BitmapData lockeddata;
2019     ULONG andstride, xorstride, bitssize;
2020     LPBYTE andbits, xorbits, androw, xorrow, srcrow;
2021     UINT x, y;
2022
2023     TRACE("(%p, %p)\n", bitmap, hicon);
2024
2025     if (!bitmap || !hicon)
2026         return InvalidParameter;
2027
2028     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead,
2029         PixelFormat32bppPARGB, &lockeddata);
2030     if (stat == Ok)
2031     {
2032         andstride = ((lockeddata.Width+31)/32)*4;
2033         xorstride = lockeddata.Width*4;
2034         bitssize = (andstride + xorstride) * lockeddata.Height;
2035
2036         andbits = GdipAlloc(bitssize);
2037
2038         if (andbits)
2039         {
2040             xorbits = andbits + andstride * lockeddata.Height;
2041
2042             for (y=0; y<lockeddata.Height; y++)
2043             {
2044                 srcrow = ((LPBYTE)lockeddata.Scan0) + lockeddata.Stride * y;
2045
2046                 androw = andbits + andstride * y;
2047                 for (x=0; x<lockeddata.Width; x++)
2048                     if (srcrow[3+4*x] >= 128)
2049                         androw[x/8] |= 1 << (7-x%8);
2050
2051                 xorrow = xorbits + xorstride * y;
2052                 memcpy(xorrow, srcrow, xorstride);
2053             }
2054
2055             *hicon = CreateIcon(NULL, lockeddata.Width, lockeddata.Height, 1, 32,
2056                 andbits, xorbits);
2057
2058             GdipFree(andbits);
2059         }
2060         else
2061             stat = OutOfMemory;
2062
2063         GdipBitmapUnlockBits(bitmap, &lockeddata);
2064     }
2065
2066     return stat;
2067 }
2068
2069 GpStatus WINGDIPAPI GdipDeleteCachedBitmap(GpCachedBitmap *cachedbmp)
2070 {
2071     TRACE("%p\n", cachedbmp);
2072
2073     if(!cachedbmp)
2074         return InvalidParameter;
2075
2076     GdipDisposeImage(cachedbmp->image);
2077     GdipFree(cachedbmp);
2078
2079     return Ok;
2080 }
2081
2082 GpStatus WINGDIPAPI GdipDrawCachedBitmap(GpGraphics *graphics,
2083     GpCachedBitmap *cachedbmp, INT x, INT y)
2084 {
2085     TRACE("%p %p %d %d\n", graphics, cachedbmp, x, y);
2086
2087     if(!graphics || !cachedbmp)
2088         return InvalidParameter;
2089
2090     return GdipDrawImage(graphics, cachedbmp->image, (REAL)x, (REAL)y);
2091 }
2092
2093 GpStatus WINGDIPAPI GdipEmfToWmfBits(HENHMETAFILE hemf, UINT cbData16,
2094     LPBYTE pData16, INT iMapMode, INT eFlags)
2095 {
2096     FIXME("(%p, %d, %p, %d, %d): stub\n", hemf, cbData16, pData16, iMapMode, eFlags);
2097     return NotImplemented;
2098 }
2099
2100 /* Internal utility function: Replace the image data of dst with that of src,
2101  * and free src. */
2102 static void move_bitmap(GpBitmap *dst, GpBitmap *src, BOOL clobber_palette)
2103 {
2104     assert(src->image.type == ImageTypeBitmap);
2105     assert(dst->image.type == ImageTypeBitmap);
2106
2107     GdipFree(dst->bitmapbits);
2108     GdipFree(dst->own_bits);
2109     DeleteDC(dst->hdc);
2110     DeleteObject(dst->hbitmap);
2111
2112     if (clobber_palette)
2113     {
2114         GdipFree(dst->image.palette);
2115         dst->image.palette = src->image.palette;
2116     }
2117     else
2118         GdipFree(src->image.palette);
2119
2120     dst->image.xres = src->image.xres;
2121     dst->image.yres = src->image.yres;
2122     dst->width = src->width;
2123     dst->height = src->height;
2124     dst->format = src->format;
2125     dst->hbitmap = src->hbitmap;
2126     dst->hdc = src->hdc;
2127     dst->bits = src->bits;
2128     dst->stride = src->stride;
2129     dst->own_bits = src->own_bits;
2130     if (dst->metadata_reader)
2131         IWICMetadataReader_Release(dst->metadata_reader);
2132     dst->metadata_reader = src->metadata_reader;
2133     GdipFree(dst->prop_item);
2134     dst->prop_item = src->prop_item;
2135     dst->prop_count = src->prop_count;
2136     if (dst->image.stream)
2137         IStream_Release(dst->image.stream);
2138     dst->image.stream = src->image.stream;
2139     dst->image.frame_count = src->image.frame_count;
2140     dst->image.current_frame = src->image.current_frame;
2141     dst->image.format = src->image.format;
2142
2143     src->image.type = ~0;
2144     GdipFree(src);
2145 }
2146
2147 static GpStatus free_image_data(GpImage *image)
2148 {
2149     if(!image)
2150         return InvalidParameter;
2151
2152     if (image->type == ImageTypeBitmap)
2153     {
2154         GdipFree(((GpBitmap*)image)->bitmapbits);
2155         GdipFree(((GpBitmap*)image)->own_bits);
2156         DeleteDC(((GpBitmap*)image)->hdc);
2157         DeleteObject(((GpBitmap*)image)->hbitmap);
2158         if (((GpBitmap*)image)->metadata_reader)
2159             IWICMetadataReader_Release(((GpBitmap*)image)->metadata_reader);
2160         GdipFree(((GpBitmap*)image)->prop_item);
2161     }
2162     else if (image->type == ImageTypeMetafile)
2163     {
2164         GpMetafile *metafile = (GpMetafile*)image;
2165         GdipFree(metafile->comment_data);
2166         DeleteEnhMetaFile(CloseEnhMetaFile(metafile->record_dc));
2167         if (!metafile->preserve_hemf)
2168             DeleteEnhMetaFile(metafile->hemf);
2169         if (metafile->record_graphics)
2170         {
2171             WARN("metafile closed while recording\n");
2172             /* not sure what to do here; for now just prevent the graphics from functioning or using this object */
2173             metafile->record_graphics->image = NULL;
2174             metafile->record_graphics->busy = TRUE;
2175         }
2176     }
2177     else
2178     {
2179         WARN("invalid image: %p\n", image);
2180         return ObjectBusy;
2181     }
2182     if (image->picture)
2183         IPicture_Release(image->picture);
2184     if (image->stream)
2185         IStream_Release(image->stream);
2186     GdipFree(image->palette);
2187
2188     return Ok;
2189 }
2190
2191 GpStatus WINGDIPAPI GdipDisposeImage(GpImage *image)
2192 {
2193     GpStatus status;
2194
2195     TRACE("%p\n", image);
2196
2197     status = free_image_data(image);
2198     if (status != Ok) return status;
2199     image->type = ~0;
2200     GdipFree(image);
2201
2202     return Ok;
2203 }
2204
2205 GpStatus WINGDIPAPI GdipFindFirstImageItem(GpImage *image, ImageItemData* item)
2206 {
2207     static int calls;
2208
2209     TRACE("(%p,%p)\n", image, item);
2210
2211     if(!image || !item)
2212         return InvalidParameter;
2213
2214     if (!(calls++))
2215         FIXME("not implemented\n");
2216
2217     return NotImplemented;
2218 }
2219
2220 GpStatus WINGDIPAPI GdipGetImageItemData(GpImage *image, ImageItemData *item)
2221 {
2222     static int calls;
2223
2224     TRACE("(%p,%p)\n", image, item);
2225
2226     if (!(calls++))
2227         FIXME("not implemented\n");
2228
2229     return NotImplemented;
2230 }
2231
2232 GpStatus WINGDIPAPI GdipGetImageBounds(GpImage *image, GpRectF *srcRect,
2233     GpUnit *srcUnit)
2234 {
2235     TRACE("%p %p %p\n", image, srcRect, srcUnit);
2236
2237     if(!image || !srcRect || !srcUnit)
2238         return InvalidParameter;
2239     if(image->type == ImageTypeMetafile){
2240         *srcRect = ((GpMetafile*)image)->bounds;
2241         *srcUnit = ((GpMetafile*)image)->unit;
2242     }
2243     else if(image->type == ImageTypeBitmap){
2244         srcRect->X = srcRect->Y = 0.0;
2245         srcRect->Width = (REAL) ((GpBitmap*)image)->width;
2246         srcRect->Height = (REAL) ((GpBitmap*)image)->height;
2247         *srcUnit = UnitPixel;
2248     }
2249     else{
2250         srcRect->X = srcRect->Y = 0.0;
2251         srcRect->Width = ipicture_pixel_width(image->picture);
2252         srcRect->Height = ipicture_pixel_height(image->picture);
2253         *srcUnit = UnitPixel;
2254     }
2255
2256     TRACE("returning (%f, %f) (%f, %f) unit type %d\n", srcRect->X, srcRect->Y,
2257           srcRect->Width, srcRect->Height, *srcUnit);
2258
2259     return Ok;
2260 }
2261
2262 GpStatus WINGDIPAPI GdipGetImageDimension(GpImage *image, REAL *width,
2263     REAL *height)
2264 {
2265     TRACE("%p %p %p\n", image, width, height);
2266
2267     if(!image || !height || !width)
2268         return InvalidParameter;
2269
2270     if(image->type == ImageTypeMetafile){
2271         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2272         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2273     }
2274     else if(image->type == ImageTypeBitmap){
2275         *height = ((GpBitmap*)image)->height;
2276         *width = ((GpBitmap*)image)->width;
2277     }
2278     else{
2279         *height = ipicture_pixel_height(image->picture);
2280         *width = ipicture_pixel_width(image->picture);
2281     }
2282
2283     TRACE("returning (%f, %f)\n", *height, *width);
2284     return Ok;
2285 }
2286
2287 GpStatus WINGDIPAPI GdipGetImageGraphicsContext(GpImage *image,
2288     GpGraphics **graphics)
2289 {
2290     HDC hdc;
2291     GpStatus stat;
2292
2293     TRACE("%p %p\n", image, graphics);
2294
2295     if(!image || !graphics)
2296         return InvalidParameter;
2297
2298     if (image->type == ImageTypeBitmap && ((GpBitmap*)image)->hbitmap)
2299     {
2300         hdc = ((GpBitmap*)image)->hdc;
2301
2302         if(!hdc){
2303             hdc = CreateCompatibleDC(0);
2304             SelectObject(hdc, ((GpBitmap*)image)->hbitmap);
2305             ((GpBitmap*)image)->hdc = hdc;
2306         }
2307
2308         stat = GdipCreateFromHDC(hdc, graphics);
2309
2310         if (stat == Ok)
2311         {
2312             (*graphics)->image = image;
2313             (*graphics)->xres = image->xres;
2314             (*graphics)->yres = image->yres;
2315         }
2316     }
2317     else if (image->type == ImageTypeMetafile)
2318         stat = METAFILE_GetGraphicsContext((GpMetafile*)image, graphics);
2319     else
2320         stat = graphics_from_image(image, graphics);
2321
2322     return stat;
2323 }
2324
2325 GpStatus WINGDIPAPI GdipGetImageHeight(GpImage *image, UINT *height)
2326 {
2327     TRACE("%p %p\n", image, height);
2328
2329     if(!image || !height)
2330         return InvalidParameter;
2331
2332     if(image->type == ImageTypeMetafile)
2333         *height = units_to_pixels(((GpMetafile*)image)->bounds.Height, ((GpMetafile*)image)->unit, image->yres);
2334     else if(image->type == ImageTypeBitmap)
2335         *height = ((GpBitmap*)image)->height;
2336     else
2337         *height = ipicture_pixel_height(image->picture);
2338
2339     TRACE("returning %d\n", *height);
2340
2341     return Ok;
2342 }
2343
2344 GpStatus WINGDIPAPI GdipGetImageHorizontalResolution(GpImage *image, REAL *res)
2345 {
2346     if(!image || !res)
2347         return InvalidParameter;
2348
2349     *res = image->xres;
2350
2351     TRACE("(%p) <-- %0.2f\n", image, *res);
2352
2353     return Ok;
2354 }
2355
2356 GpStatus WINGDIPAPI GdipGetImagePaletteSize(GpImage *image, INT *size)
2357 {
2358     TRACE("%p %p\n", image, size);
2359
2360     if(!image || !size)
2361         return InvalidParameter;
2362
2363     if (!image->palette || image->palette->Count == 0)
2364         *size = sizeof(ColorPalette);
2365     else
2366         *size = sizeof(UINT)*2 + sizeof(ARGB)*image->palette->Count;
2367
2368     TRACE("<-- %u\n", *size);
2369
2370     return Ok;
2371 }
2372
2373 /* FIXME: test this function for non-bitmap types */
2374 GpStatus WINGDIPAPI GdipGetImagePixelFormat(GpImage *image, PixelFormat *format)
2375 {
2376     TRACE("%p %p\n", image, format);
2377
2378     if(!image || !format)
2379         return InvalidParameter;
2380
2381     if(image->type != ImageTypeBitmap)
2382         *format = PixelFormat24bppRGB;
2383     else
2384         *format = ((GpBitmap*) image)->format;
2385
2386     return Ok;
2387 }
2388
2389 GpStatus WINGDIPAPI GdipGetImageRawFormat(GpImage *image, GUID *format)
2390 {
2391     TRACE("(%p, %p)\n", image, format);
2392
2393     if(!image || !format)
2394         return InvalidParameter;
2395
2396     memcpy(format, &image->format, sizeof(GUID));
2397
2398     return Ok;
2399 }
2400
2401 GpStatus WINGDIPAPI GdipGetImageType(GpImage *image, ImageType *type)
2402 {
2403     TRACE("%p %p\n", image, type);
2404
2405     if(!image || !type)
2406         return InvalidParameter;
2407
2408     *type = image->type;
2409
2410     return Ok;
2411 }
2412
2413 GpStatus WINGDIPAPI GdipGetImageVerticalResolution(GpImage *image, REAL *res)
2414 {
2415     if(!image || !res)
2416         return InvalidParameter;
2417
2418     *res = image->yres;
2419
2420     TRACE("(%p) <-- %0.2f\n", image, *res);
2421
2422     return Ok;
2423 }
2424
2425 GpStatus WINGDIPAPI GdipGetImageWidth(GpImage *image, UINT *width)
2426 {
2427     TRACE("%p %p\n", image, width);
2428
2429     if(!image || !width)
2430         return InvalidParameter;
2431
2432     if(image->type == ImageTypeMetafile)
2433         *width = units_to_pixels(((GpMetafile*)image)->bounds.Width, ((GpMetafile*)image)->unit, image->xres);
2434     else if(image->type == ImageTypeBitmap)
2435         *width = ((GpBitmap*)image)->width;
2436     else
2437         *width = ipicture_pixel_width(image->picture);
2438
2439     TRACE("returning %d\n", *width);
2440
2441     return Ok;
2442 }
2443
2444 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromMetafile(GpMetafile * metafile,
2445     MetafileHeader * header)
2446 {
2447     static int calls;
2448
2449     TRACE("(%p, %p)\n", metafile, header);
2450
2451     if(!metafile || !header)
2452         return InvalidParameter;
2453
2454     if(!(calls++))
2455         FIXME("not implemented\n");
2456
2457     memset(header, 0, sizeof(MetafileHeader));
2458
2459     return Ok;
2460 }
2461
2462 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromEmf(HENHMETAFILE hEmf,
2463     MetafileHeader *header)
2464 {
2465     static int calls;
2466
2467     if(!hEmf || !header)
2468         return InvalidParameter;
2469
2470     if(!(calls++))
2471         FIXME("not implemented\n");
2472
2473     memset(header, 0, sizeof(MetafileHeader));
2474
2475     return Ok;
2476 }
2477
2478 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromFile(GDIPCONST WCHAR *filename,
2479     MetafileHeader *header)
2480 {
2481     static int calls;
2482
2483     TRACE("(%s,%p)\n", debugstr_w(filename), header);
2484
2485     if(!filename || !header)
2486         return InvalidParameter;
2487
2488     if(!(calls++))
2489         FIXME("not implemented\n");
2490
2491     memset(header, 0, sizeof(MetafileHeader));
2492
2493     return Ok;
2494 }
2495
2496 GpStatus WINGDIPAPI GdipGetMetafileHeaderFromStream(IStream *stream,
2497     MetafileHeader *header)
2498 {
2499     static int calls;
2500
2501     TRACE("(%p,%p)\n", stream, header);
2502
2503     if(!stream || !header)
2504         return InvalidParameter;
2505
2506     if(!(calls++))
2507         FIXME("not implemented\n");
2508
2509     memset(header, 0, sizeof(MetafileHeader));
2510
2511     return Ok;
2512 }
2513
2514 GpStatus WINGDIPAPI GdipGetPropertyCount(GpImage *image, UINT *num)
2515 {
2516     TRACE("(%p, %p)\n", image, num);
2517
2518     if (!image || !num) return InvalidParameter;
2519
2520     *num = 0;
2521
2522     if (image->type == ImageTypeBitmap)
2523     {
2524         if (((GpBitmap *)image)->prop_item)
2525         {
2526             *num = ((GpBitmap *)image)->prop_count;
2527             return Ok;
2528         }
2529
2530         if (((GpBitmap *)image)->metadata_reader)
2531             IWICMetadataReader_GetCount(((GpBitmap *)image)->metadata_reader, num);
2532     }
2533
2534     return Ok;
2535 }
2536
2537 GpStatus WINGDIPAPI GdipGetPropertyIdList(GpImage *image, UINT num, PROPID *list)
2538 {
2539     HRESULT hr;
2540     IWICMetadataReader *reader;
2541     IWICEnumMetadataItem *enumerator;
2542     UINT prop_count, i, items_returned;
2543
2544     TRACE("(%p, %u, %p)\n", image, num, list);
2545
2546     if (!image || !list) return InvalidParameter;
2547
2548     if (image->type != ImageTypeBitmap)
2549     {
2550         FIXME("Not implemented for type %d\n", image->type);
2551         return NotImplemented;
2552     }
2553
2554     if (((GpBitmap *)image)->prop_item)
2555     {
2556         if (num != ((GpBitmap *)image)->prop_count) return InvalidParameter;
2557
2558         for (i = 0; i < num; i++)
2559         {
2560             list[i] = ((GpBitmap *)image)->prop_item[i].id;
2561         }
2562
2563         return Ok;
2564     }
2565
2566     reader = ((GpBitmap *)image)->metadata_reader;
2567     if (!reader)
2568     {
2569         if (num != 0) return InvalidParameter;
2570         return Ok;
2571     }
2572
2573     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2574     if (FAILED(hr)) return hresult_to_status(hr);
2575
2576     if (num != prop_count) return InvalidParameter;
2577
2578     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2579     if (FAILED(hr)) return hresult_to_status(hr);
2580
2581     IWICEnumMetadataItem_Reset(enumerator);
2582
2583     for (i = 0; i < num; i++)
2584     {
2585         PROPVARIANT id;
2586
2587         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, NULL, &items_returned);
2588         if (hr != S_OK) break;
2589
2590         if (id.vt != VT_UI2)
2591         {
2592             FIXME("not supported propvariant type for id: %u\n", id.vt);
2593             list[i] = 0;
2594             continue;
2595         }
2596         list[i] = id.u.uiVal;
2597     }
2598
2599     IWICEnumMetadataItem_Release(enumerator);
2600
2601     return hr == S_OK ? Ok : hresult_to_status(hr);
2602 }
2603
2604 static UINT propvariant_size(PROPVARIANT *value)
2605 {
2606     switch (value->vt & ~VT_VECTOR)
2607     {
2608     case VT_EMPTY:
2609         return 0;
2610     case VT_I1:
2611     case VT_UI1:
2612         if (!(value->vt & VT_VECTOR)) return 1;
2613         return value->u.caub.cElems;
2614     case VT_I2:
2615     case VT_UI2:
2616         if (!(value->vt & VT_VECTOR)) return 2;
2617         return value->u.caui.cElems * 2;
2618     case VT_I4:
2619     case VT_UI4:
2620     case VT_R4:
2621         if (!(value->vt & VT_VECTOR)) return 4;
2622         return value->u.caul.cElems * 4;
2623     case VT_I8:
2624     case VT_UI8:
2625     case VT_R8:
2626         if (!(value->vt & VT_VECTOR)) return 8;
2627         return value->u.cauh.cElems * 8;
2628     case VT_LPSTR:
2629         return value->u.pszVal ? strlen(value->u.pszVal) + 1 : 0;
2630     case VT_BLOB:
2631         return value->u.blob.cbSize;
2632     default:
2633         FIXME("not supported variant type %d\n", value->vt);
2634         return 0;
2635     }
2636 }
2637
2638 GpStatus WINGDIPAPI GdipGetPropertyItemSize(GpImage *image, PROPID propid, UINT *size)
2639 {
2640     HRESULT hr;
2641     IWICMetadataReader *reader;
2642     PROPVARIANT id, value;
2643
2644     TRACE("(%p,%#x,%p)\n", image, propid, size);
2645
2646     if (!size || !image) return InvalidParameter;
2647
2648     if (image->type != ImageTypeBitmap)
2649     {
2650         FIXME("Not implemented for type %d\n", image->type);
2651         return NotImplemented;
2652     }
2653
2654     if (((GpBitmap *)image)->prop_item)
2655     {
2656         UINT i;
2657
2658         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2659         {
2660             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2661             {
2662                 *size = sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2663                 return Ok;
2664             }
2665         }
2666
2667         return PropertyNotFound;
2668     }
2669
2670     reader = ((GpBitmap *)image)->metadata_reader;
2671     if (!reader) return PropertyNotFound;
2672
2673     id.vt = VT_UI2;
2674     id.u.uiVal = propid;
2675     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2676     if (FAILED(hr)) return PropertyNotFound;
2677
2678     *size = propvariant_size(&value);
2679     if (*size) *size += sizeof(PropertyItem);
2680     PropVariantClear(&value);
2681
2682     return Ok;
2683 }
2684
2685 #ifndef PropertyTagTypeSByte
2686 #define PropertyTagTypeSByte  6
2687 #define PropertyTagTypeSShort 8
2688 #define PropertyTagTypeFloat  11
2689 #define PropertyTagTypeDouble 12
2690 #endif
2691
2692 static UINT vt_to_itemtype(UINT vt)
2693 {
2694     static const struct
2695     {
2696         UINT vt, type;
2697     } vt2type[] =
2698     {
2699         { VT_I1, PropertyTagTypeSByte },
2700         { VT_UI1, PropertyTagTypeByte },
2701         { VT_I2, PropertyTagTypeSShort },
2702         { VT_UI2, PropertyTagTypeShort },
2703         { VT_I4, PropertyTagTypeSLONG },
2704         { VT_UI4, PropertyTagTypeLong },
2705         { VT_I8, PropertyTagTypeSRational },
2706         { VT_UI8, PropertyTagTypeRational },
2707         { VT_R4, PropertyTagTypeFloat },
2708         { VT_R8, PropertyTagTypeDouble },
2709         { VT_LPSTR, PropertyTagTypeASCII },
2710         { VT_BLOB, PropertyTagTypeUndefined }
2711     };
2712     UINT i;
2713     for (i = 0; i < sizeof(vt2type)/sizeof(vt2type[0]); i++)
2714     {
2715         if (vt2type[i].vt == vt) return vt2type[i].type;
2716     }
2717     FIXME("not supported variant type %u\n", vt);
2718     return 0;
2719 }
2720
2721 static GpStatus propvariant_to_item(PROPVARIANT *value, PropertyItem *item,
2722                                     UINT size, PROPID id)
2723 {
2724     UINT item_size, item_type;
2725
2726     item_size = propvariant_size(value);
2727     if (size != item_size + sizeof(PropertyItem)) return InvalidParameter;
2728
2729     item_type = vt_to_itemtype(value->vt & ~VT_VECTOR);
2730     if (!item_type) return InvalidParameter;
2731
2732     item->value = item + 1;
2733
2734     switch (value->vt & ~VT_VECTOR)
2735     {
2736     case VT_I1:
2737     case VT_UI1:
2738         if (!(value->vt & VT_VECTOR))
2739             *(BYTE *)item->value = value->u.bVal;
2740         else
2741             memcpy(item->value, value->u.caub.pElems, item_size);
2742         break;
2743     case VT_I2:
2744     case VT_UI2:
2745         if (!(value->vt & VT_VECTOR))
2746             *(USHORT *)item->value = value->u.uiVal;
2747         else
2748             memcpy(item->value, value->u.caui.pElems, item_size);
2749         break;
2750     case VT_I4:
2751     case VT_UI4:
2752     case VT_R4:
2753         if (!(value->vt & VT_VECTOR))
2754             *(ULONG *)item->value = value->u.ulVal;
2755         else
2756             memcpy(item->value, value->u.caul.pElems, item_size);
2757         break;
2758     case VT_I8:
2759     case VT_UI8:
2760     case VT_R8:
2761         if (!(value->vt & VT_VECTOR))
2762             *(ULONGLONG *)item->value = value->u.uhVal.QuadPart;
2763         else
2764             memcpy(item->value, value->u.cauh.pElems, item_size);
2765         break;
2766     case VT_LPSTR:
2767         memcpy(item->value, value->u.pszVal, item_size);
2768         break;
2769     case VT_BLOB:
2770         memcpy(item->value, value->u.blob.pBlobData, item_size);
2771         break;
2772     default:
2773         FIXME("not supported variant type %d\n", value->vt);
2774         return InvalidParameter;
2775     }
2776
2777     item->length = item_size;
2778     item->type = item_type;
2779     item->id = id;
2780
2781     return Ok;
2782 }
2783
2784 GpStatus WINGDIPAPI GdipGetPropertyItem(GpImage *image, PROPID propid, UINT size,
2785                                         PropertyItem *buffer)
2786 {
2787     GpStatus stat;
2788     HRESULT hr;
2789     IWICMetadataReader *reader;
2790     PROPVARIANT id, value;
2791
2792     TRACE("(%p,%#x,%u,%p)\n", image, propid, size, buffer);
2793
2794     if (!image || !buffer) return InvalidParameter;
2795
2796     if (image->type != ImageTypeBitmap)
2797     {
2798         FIXME("Not implemented for type %d\n", image->type);
2799         return NotImplemented;
2800     }
2801
2802     if (((GpBitmap *)image)->prop_item)
2803     {
2804         UINT i;
2805
2806         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2807         {
2808             if (propid == ((GpBitmap *)image)->prop_item[i].id)
2809             {
2810                 if (size != sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length)
2811                     return InvalidParameter;
2812
2813                 *buffer = ((GpBitmap *)image)->prop_item[i];
2814                 buffer->value = buffer + 1;
2815                 memcpy(buffer->value, ((GpBitmap *)image)->prop_item[i].value, buffer->length);
2816                 return Ok;
2817             }
2818         }
2819
2820         return PropertyNotFound;
2821     }
2822
2823     reader = ((GpBitmap *)image)->metadata_reader;
2824     if (!reader) return PropertyNotFound;
2825
2826     id.vt = VT_UI2;
2827     id.u.uiVal = propid;
2828     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
2829     if (FAILED(hr)) return PropertyNotFound;
2830
2831     stat = propvariant_to_item(&value, buffer, size, propid);
2832     PropVariantClear(&value);
2833
2834     return stat;
2835 }
2836
2837 GpStatus WINGDIPAPI GdipGetPropertySize(GpImage *image, UINT *size, UINT *count)
2838 {
2839     HRESULT hr;
2840     IWICMetadataReader *reader;
2841     IWICEnumMetadataItem *enumerator;
2842     UINT prop_count, prop_size, i;
2843     PROPVARIANT id, value;
2844
2845     TRACE("(%p,%p,%p)\n", image, size, count);
2846
2847     if (!image || !size || !count) return InvalidParameter;
2848
2849     if (image->type != ImageTypeBitmap)
2850     {
2851         FIXME("Not implemented for type %d\n", image->type);
2852         return NotImplemented;
2853     }
2854
2855     if (((GpBitmap *)image)->prop_item)
2856     {
2857         *count = ((GpBitmap *)image)->prop_count;
2858         *size = 0;
2859
2860         for (i = 0; i < ((GpBitmap *)image)->prop_count; i++)
2861         {
2862             *size += sizeof(PropertyItem) + ((GpBitmap *)image)->prop_item[i].length;
2863         }
2864
2865         return Ok;
2866     }
2867
2868     reader = ((GpBitmap *)image)->metadata_reader;
2869     if (!reader) return PropertyNotFound;
2870
2871     hr = IWICMetadataReader_GetCount(reader, &prop_count);
2872     if (FAILED(hr)) return hresult_to_status(hr);
2873
2874     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2875     if (FAILED(hr)) return hresult_to_status(hr);
2876
2877     IWICEnumMetadataItem_Reset(enumerator);
2878
2879     prop_size = 0;
2880
2881     PropVariantInit(&id);
2882     PropVariantInit(&value);
2883
2884     for (i = 0; i < prop_count; i++)
2885     {
2886         UINT items_returned, item_size;
2887
2888         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2889         if (hr != S_OK) break;
2890
2891         item_size = propvariant_size(&value);
2892         if (item_size) prop_size += sizeof(PropertyItem) + item_size;
2893
2894         PropVariantClear(&id);
2895         PropVariantClear(&value);
2896     }
2897
2898     IWICEnumMetadataItem_Release(enumerator);
2899
2900     if (hr != S_OK) return PropertyNotFound;
2901
2902     *count = prop_count;
2903     *size = prop_size;
2904     return Ok;
2905 }
2906
2907 GpStatus WINGDIPAPI GdipGetAllPropertyItems(GpImage *image, UINT size,
2908                                             UINT count, PropertyItem *buf)
2909 {
2910     GpStatus status;
2911     HRESULT hr;
2912     IWICMetadataReader *reader;
2913     IWICEnumMetadataItem *enumerator;
2914     UINT prop_count, prop_size, i;
2915     PROPVARIANT id, value;
2916     char *item_value;
2917
2918     TRACE("(%p,%u,%u,%p)\n", image, size, count, buf);
2919
2920     if (!image || !buf) return InvalidParameter;
2921
2922     if (image->type != ImageTypeBitmap)
2923     {
2924         FIXME("Not implemented for type %d\n", image->type);
2925         return NotImplemented;
2926     }
2927
2928     status = GdipGetPropertySize(image, &prop_size, &prop_count);
2929     if (status != Ok) return status;
2930
2931     if (prop_count != count || prop_size != size) return InvalidParameter;
2932
2933     if (((GpBitmap *)image)->prop_item)
2934     {
2935         memcpy(buf, ((GpBitmap *)image)->prop_item, prop_size);
2936
2937         item_value = (char *)(buf + prop_count);
2938
2939         for (i = 0; i < prop_count; i++)
2940         {
2941             buf[i].value = item_value;
2942             item_value += buf[i].length;
2943         }
2944
2945         return Ok;
2946     }
2947
2948     reader = ((GpBitmap *)image)->metadata_reader;
2949     if (!reader) return PropertyNotFound;
2950
2951     hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
2952     if (FAILED(hr)) return hresult_to_status(hr);
2953
2954     IWICEnumMetadataItem_Reset(enumerator);
2955
2956     item_value = (char *)(buf + prop_count);
2957
2958     PropVariantInit(&id);
2959     PropVariantInit(&value);
2960
2961     for (i = 0; i < prop_count; i++)
2962     {
2963         PropertyItem *item;
2964         UINT items_returned, item_size;
2965
2966         hr = IWICEnumMetadataItem_Next(enumerator, 1, NULL, &id, &value, &items_returned);
2967         if (hr != S_OK) break;
2968
2969         if (id.vt != VT_UI2)
2970         {
2971             FIXME("not supported propvariant type for id: %u\n", id.vt);
2972             continue;
2973         }
2974
2975         item_size = propvariant_size(&value);
2976         if (item_size)
2977         {
2978             item = HeapAlloc(GetProcessHeap(), 0, item_size + sizeof(*item));
2979
2980             propvariant_to_item(&value, item, item_size + sizeof(*item), id.u.uiVal);
2981             buf[i].id = item->id;
2982             buf[i].type = item->type;
2983             buf[i].length = item_size;
2984             buf[i].value = item_value;
2985             memcpy(item_value, item->value, item_size);
2986             item_value += item_size;
2987
2988             HeapFree(GetProcessHeap(), 0, item);
2989         }
2990
2991         PropVariantClear(&id);
2992         PropVariantClear(&value);
2993     }
2994
2995     IWICEnumMetadataItem_Release(enumerator);
2996
2997     if (hr != S_OK) return PropertyNotFound;
2998
2999     return Ok;
3000 }
3001
3002 struct image_format_dimension
3003 {
3004     const GUID *format;
3005     const GUID *dimension;
3006 };
3007
3008 static const struct image_format_dimension image_format_dimensions[] =
3009 {
3010     {&ImageFormatGIF, &FrameDimensionTime},
3011     {&ImageFormatIcon, &FrameDimensionResolution},
3012     {NULL}
3013 };
3014
3015 GpStatus WINGDIPAPI GdipImageGetFrameCount(GpImage *image,
3016     GDIPCONST GUID* dimensionID, UINT* count)
3017 {
3018     TRACE("(%p,%s,%p)\n", image, debugstr_guid(dimensionID), count);
3019
3020     if(!image || !count)
3021         return InvalidParameter;
3022
3023     if (!dimensionID ||
3024         IsEqualGUID(dimensionID, &image->format) ||
3025         IsEqualGUID(dimensionID, &FrameDimensionPage) ||
3026         IsEqualGUID(dimensionID, &FrameDimensionTime))
3027     {
3028         *count = image->frame_count;
3029         return Ok;
3030     }
3031
3032     return InvalidParameter;
3033 }
3034
3035 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsCount(GpImage *image,
3036     UINT* count)
3037 {
3038     TRACE("(%p, %p)\n", image, count);
3039
3040     /* Native gdiplus 1.1 does not yet support multiple frame dimensions. */
3041
3042     if(!image || !count)
3043         return InvalidParameter;
3044
3045     *count = 1;
3046
3047     return Ok;
3048 }
3049
3050 GpStatus WINGDIPAPI GdipImageGetFrameDimensionsList(GpImage* image,
3051     GUID* dimensionIDs, UINT count)
3052 {
3053     int i;
3054     const GUID *result=NULL;
3055
3056     TRACE("(%p,%p,%u)\n", image, dimensionIDs, count);
3057
3058     if(!image || !dimensionIDs || count != 1)
3059         return InvalidParameter;
3060
3061     for (i=0; image_format_dimensions[i].format; i++)
3062     {
3063         if (IsEqualGUID(&image->format, image_format_dimensions[i].format))
3064         {
3065             result = image_format_dimensions[i].dimension;
3066             break;
3067         }
3068     }
3069
3070     if (!result)
3071         result = &FrameDimensionPage;
3072
3073     memcpy(dimensionIDs, result, sizeof(GUID));
3074
3075     return Ok;
3076 }
3077
3078 GpStatus WINGDIPAPI GdipLoadImageFromFile(GDIPCONST WCHAR* filename,
3079                                           GpImage **image)
3080 {
3081     GpStatus stat;
3082     IStream *stream;
3083
3084     TRACE("(%s) %p\n", debugstr_w(filename), image);
3085
3086     if (!filename || !image)
3087         return InvalidParameter;
3088
3089     stat = GdipCreateStreamOnFile(filename, GENERIC_READ, &stream);
3090
3091     if (stat != Ok)
3092         return stat;
3093
3094     stat = GdipLoadImageFromStream(stream, image);
3095
3096     IStream_Release(stream);
3097
3098     return stat;
3099 }
3100
3101 /* FIXME: no icm handling */
3102 GpStatus WINGDIPAPI GdipLoadImageFromFileICM(GDIPCONST WCHAR* filename,GpImage **image)
3103 {
3104     TRACE("(%s) %p\n", debugstr_w(filename), image);
3105
3106     return GdipLoadImageFromFile(filename, image);
3107 }
3108
3109 static void add_property(GpBitmap *bitmap, PropertyItem *item)
3110 {
3111     UINT prop_size, prop_count;
3112     PropertyItem *prop_item;
3113
3114     if (bitmap->prop_item == NULL)
3115     {
3116         prop_size = prop_count = 0;
3117         prop_item = GdipAlloc(item->length + sizeof(PropertyItem));
3118         if (!prop_item) return;
3119     }
3120     else
3121     {
3122         UINT i;
3123         char *item_value;
3124
3125         GdipGetPropertySize((GpImage *)bitmap, &prop_size, &prop_count);
3126
3127         prop_item = GdipAlloc(prop_size + item->length + sizeof(PropertyItem));
3128         if (!prop_item) return;
3129         memcpy(prop_item, bitmap->prop_item, sizeof(PropertyItem) * bitmap->prop_count);
3130         prop_size -= sizeof(PropertyItem) * bitmap->prop_count;
3131         memcpy(prop_item + prop_count + 1, bitmap->prop_item + prop_count, prop_size);
3132
3133         item_value = (char *)(prop_item + prop_count + 1);
3134
3135         for (i = 0; i < prop_count; i++)
3136         {
3137             prop_item[i].value = item_value;
3138             item_value += prop_item[i].length;
3139         }
3140     }
3141
3142     prop_item[prop_count].id = item->id;
3143     prop_item[prop_count].type = item->type;
3144     prop_item[prop_count].length = item->length;
3145     prop_item[prop_count].value = (char *)(prop_item + prop_count + 1) + prop_size;
3146     memcpy(prop_item[prop_count].value, item->value, item->length);
3147
3148     GdipFree(bitmap->prop_item);
3149     bitmap->prop_item = prop_item;
3150     bitmap->prop_count++;
3151 }
3152
3153 static BOOL get_bool_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3154 {
3155     HRESULT hr;
3156     GUID format;
3157     PROPVARIANT id, value;
3158     BOOL ret = FALSE;
3159
3160     IWICMetadataReader_GetMetadataFormat(reader, &format);
3161     if (!IsEqualGUID(&format, guid)) return FALSE;
3162
3163     PropVariantInit(&id);
3164     PropVariantInit(&value);
3165
3166     id.vt = VT_LPWSTR;
3167     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3168     if (!id.u.pwszVal) return FALSE;
3169     lstrcpyW(id.u.pwszVal, prop_name);
3170     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3171     if (hr == S_OK && value.vt == VT_BOOL)
3172         ret = value.u.boolVal;
3173
3174     PropVariantClear(&id);
3175     PropVariantClear(&value);
3176
3177     return ret;
3178 }
3179
3180 static PropertyItem *get_property(IWICMetadataReader *reader, const GUID *guid, const WCHAR *prop_name)
3181 {
3182     HRESULT hr;
3183     GUID format;
3184     PROPVARIANT id, value;
3185     PropertyItem *item = NULL;
3186
3187     IWICMetadataReader_GetMetadataFormat(reader, &format);
3188     if (!IsEqualGUID(&format, guid)) return NULL;
3189
3190     PropVariantInit(&id);
3191     PropVariantInit(&value);
3192
3193     id.vt = VT_LPWSTR;
3194     id.u.pwszVal = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(prop_name) + 1) * sizeof(WCHAR));
3195     if (!id.u.pwszVal) return NULL;
3196     lstrcpyW(id.u.pwszVal, prop_name);
3197     hr = IWICMetadataReader_GetValue(reader, NULL, &id, &value);
3198     if (hr == S_OK)
3199     {
3200         UINT item_size = propvariant_size(&value);
3201         if (item_size)
3202         {
3203             item_size += sizeof(*item);
3204             item = GdipAlloc(item_size);
3205             if (propvariant_to_item(&value, item, item_size, 0) != Ok)
3206             {
3207                 GdipFree(item);
3208                 item = NULL;
3209             }
3210         }
3211     }
3212
3213     PropVariantClear(&id);
3214     PropVariantClear(&value);
3215
3216     return item;
3217 }
3218
3219 static PropertyItem *get_gif_comment(IWICMetadataReader *reader)
3220 {
3221     static const WCHAR textentryW[] = { 'T','e','x','t','E','n','t','r','y',0 };
3222     PropertyItem *comment;
3223
3224     comment = get_property(reader, &GUID_MetadataFormatGifComment, textentryW);
3225     if (comment)
3226         comment->id = PropertyTagExifUserComment;
3227
3228     return comment;
3229 }
3230
3231 static PropertyItem *get_gif_loopcount(IWICMetadataReader *reader)
3232 {
3233     static const WCHAR applicationW[] = { 'A','p','p','l','i','c','a','t','i','o','n',0 };
3234     static const WCHAR dataW[] = { 'D','a','t','a',0 };
3235     PropertyItem *appext = NULL, *appdata = NULL, *loop = NULL;
3236
3237     appext = get_property(reader, &GUID_MetadataFormatAPE, applicationW);
3238     if (appext)
3239     {
3240         if (appext->type == PropertyTagTypeByte && appext->length == 11 &&
3241             (!memcmp(appext->value, "NETSCAPE2.0", 11) || !memcmp(appext->value, "ANIMEXTS1.0", 11)))
3242         {
3243             appdata = get_property(reader, &GUID_MetadataFormatAPE, dataW);
3244             if (appdata)
3245             {
3246                 if (appdata->type == PropertyTagTypeByte && appdata->length == 4)
3247                 {
3248                     BYTE *data = appdata->value;
3249                     if (data[0] == 3 && data[1] == 1)
3250                     {
3251                         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3252                         if (loop)
3253                         {
3254                             loop->type = PropertyTagTypeShort;
3255                             loop->id = PropertyTagLoopCount;
3256                             loop->length = sizeof(SHORT);
3257                             loop->value = loop + 1;
3258                             *(SHORT *)loop->value = data[2] | (data[3] << 8);
3259                         }
3260                     }
3261                 }
3262             }
3263         }
3264     }
3265
3266     GdipFree(appext);
3267     GdipFree(appdata);
3268
3269     return loop;
3270 }
3271
3272 static PropertyItem *get_gif_background(IWICMetadataReader *reader)
3273 {
3274     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 };
3275     PropertyItem *background;
3276
3277     background = get_property(reader, &GUID_MetadataFormatLSD, backgroundW);
3278     if (background)
3279         background->id = PropertyTagIndexBackground;
3280
3281     return background;
3282 }
3283
3284 static PropertyItem *get_gif_palette(IWICBitmapDecoder *decoder, IWICMetadataReader *reader)
3285 {
3286     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 };
3287     HRESULT hr;
3288     IWICImagingFactory *factory;
3289     IWICPalette *palette;
3290     UINT count = 0;
3291     WICColor colors[256];
3292
3293     if (!get_bool_property(reader, &GUID_MetadataFormatLSD, global_flagW))
3294         return NULL;
3295
3296     hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER,
3297                           &IID_IWICImagingFactory, (void **)&factory);
3298     if (hr != S_OK) return NULL;
3299
3300     hr = IWICImagingFactory_CreatePalette(factory, &palette);
3301     if (hr == S_OK)
3302     {
3303         hr = IWICBitmapDecoder_CopyPalette(decoder, palette);
3304         if (hr == S_OK)
3305             IWICPalette_GetColors(palette, 256, colors, &count);
3306
3307         IWICPalette_Release(palette);
3308     }
3309
3310     IWICImagingFactory_Release(factory);
3311
3312     if (count)
3313     {
3314         PropertyItem *pal;
3315         UINT i;
3316         BYTE *rgb;
3317
3318         pal = GdipAlloc(sizeof(*pal) + count * 3);
3319         if (!pal) return NULL;
3320         pal->type = PropertyTagTypeByte;
3321         pal->id = PropertyTagGlobalPalette;
3322         pal->value = pal + 1;
3323         pal->length = count * 3;
3324
3325         rgb = pal->value;
3326
3327         for (i = 0; i < count; i++)
3328         {
3329             rgb[i*3] = (colors[i] >> 16) & 0xff;
3330             rgb[i*3 + 1] = (colors[i] >> 8) & 0xff;
3331             rgb[i*3 + 2] = colors[i] & 0xff;
3332         }
3333
3334         return pal;
3335     }
3336
3337     return NULL;
3338 }
3339
3340 static PropertyItem *get_gif_transparent_idx(IWICMetadataReader *reader)
3341 {
3342     static const WCHAR transparency_flagW[] = { 'T','r','a','n','s','p','a','r','e','n','c','y','F','l','a','g',0 };
3343     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 };
3344     PropertyItem *index = NULL;
3345
3346     if (get_bool_property(reader, &GUID_MetadataFormatGCE, transparency_flagW))
3347     {
3348         index = get_property(reader, &GUID_MetadataFormatGCE, colorW);
3349         if (index)
3350             index->id = PropertyTagIndexTransparent;
3351     }
3352     return index;
3353 }
3354
3355 static LONG get_gif_frame_delay(IWICBitmapFrameDecode *frame)
3356 {
3357     static const WCHAR delayW[] = { 'D','e','l','a','y',0 };
3358     HRESULT hr;
3359     IWICMetadataBlockReader *block_reader;
3360     IWICMetadataReader *reader;
3361     UINT block_count, i;
3362     PropertyItem *delay;
3363     LONG value = 0;
3364
3365     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3366     if (hr == S_OK)
3367     {
3368         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3369         if (hr == S_OK)
3370         {
3371             for (i = 0; i < block_count; i++)
3372             {
3373                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3374                 if (hr == S_OK)
3375                 {
3376                     delay = get_property(reader, &GUID_MetadataFormatGCE, delayW);
3377                     if (delay)
3378                     {
3379                         if (delay->type == PropertyTagTypeShort && delay->length == 2)
3380                             value = *(SHORT *)delay->value;
3381
3382                         GdipFree(delay);
3383                     }
3384                     IWICMetadataReader_Release(reader);
3385                 }
3386             }
3387         }
3388         IWICMetadataBlockReader_Release(block_reader);
3389     }
3390
3391     return value;
3392 }
3393
3394 static void gif_metadata_reader(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT active_frame)
3395 {
3396     HRESULT hr;
3397     IWICBitmapFrameDecode *frame;
3398     IWICMetadataBlockReader *block_reader;
3399     IWICMetadataReader *reader;
3400     UINT frame_count, block_count, i;
3401     PropertyItem *delay = NULL, *comment = NULL, *background = NULL;
3402     PropertyItem *transparent_idx = NULL, *loop = NULL, *palette = NULL;
3403
3404     IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3405     if (frame_count > 1)
3406     {
3407         delay = GdipAlloc(sizeof(*delay) + frame_count * sizeof(LONG));
3408         if (delay)
3409         {
3410             LONG *value;
3411
3412             delay->type = PropertyTagTypeLong;
3413             delay->id = PropertyTagFrameDelay;
3414             delay->length = frame_count * sizeof(LONG);
3415             delay->value = delay + 1;
3416
3417             value = delay->value;
3418
3419             for (i = 0; i < frame_count; i++)
3420             {
3421                 hr = IWICBitmapDecoder_GetFrame(decoder, i, &frame);
3422                 if (hr == S_OK)
3423                 {
3424                     value[i] = get_gif_frame_delay(frame);
3425                     IWICBitmapFrameDecode_Release(frame);
3426                 }
3427                 else value[i] = 0;
3428             }
3429         }
3430     }
3431
3432     hr = IWICBitmapDecoder_QueryInterface(decoder, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3433     if (hr == S_OK)
3434     {
3435         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3436         if (hr == S_OK)
3437         {
3438             for (i = 0; i < block_count; i++)
3439             {
3440                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3441                 if (hr == S_OK)
3442                 {
3443                     if (!comment)
3444                         comment = get_gif_comment(reader);
3445
3446                     if (frame_count > 1 && !loop)
3447                         loop = get_gif_loopcount(reader);
3448
3449                     if (!background)
3450                         background = get_gif_background(reader);
3451
3452                     if (!palette)
3453                         palette = get_gif_palette(decoder, reader);
3454
3455                     IWICMetadataReader_Release(reader);
3456                 }
3457             }
3458         }
3459         IWICMetadataBlockReader_Release(block_reader);
3460     }
3461
3462     if (frame_count > 1 && !loop)
3463     {
3464         loop = GdipAlloc(sizeof(*loop) + sizeof(SHORT));
3465         if (loop)
3466         {
3467             loop->type = PropertyTagTypeShort;
3468             loop->id = PropertyTagLoopCount;
3469             loop->length = sizeof(SHORT);
3470             loop->value = loop + 1;
3471             *(SHORT *)loop->value = 1;
3472         }
3473     }
3474
3475     if (delay) add_property(bitmap, delay);
3476     if (comment) add_property(bitmap, comment);
3477     if (loop) add_property(bitmap, loop);
3478     if (palette) add_property(bitmap, palette);
3479     if (background) add_property(bitmap, background);
3480
3481     GdipFree(delay);
3482     GdipFree(comment);
3483     GdipFree(loop);
3484     GdipFree(palette);
3485     GdipFree(background);
3486
3487     /* Win7 gdiplus always returns transparent color index from frame 0 */
3488     hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
3489     if (hr != S_OK) return;
3490
3491     hr = IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader);
3492     if (hr == S_OK)
3493     {
3494         hr = IWICMetadataBlockReader_GetCount(block_reader, &block_count);
3495         if (hr == S_OK)
3496         {
3497             for (i = 0; i < block_count; i++)
3498             {
3499                 hr = IWICMetadataBlockReader_GetReaderByIndex(block_reader, i, &reader);
3500                 if (hr == S_OK)
3501                 {
3502                     if (!transparent_idx)
3503                         transparent_idx = get_gif_transparent_idx(reader);
3504
3505                     IWICMetadataReader_Release(reader);
3506                 }
3507             }
3508         }
3509         IWICMetadataBlockReader_Release(block_reader);
3510     }
3511
3512     if (transparent_idx) add_property(bitmap, transparent_idx);
3513     GdipFree(transparent_idx);
3514
3515     IWICBitmapFrameDecode_Release(frame);
3516 }
3517
3518 typedef void (*metadata_reader_func)(GpBitmap *bitmap, IWICBitmapDecoder *decoder, UINT frame);
3519
3520 static GpStatus decode_image_wic(IStream *stream, GDIPCONST CLSID *clsid,
3521     UINT active_frame, metadata_reader_func metadata_reader, GpImage **image)
3522 {
3523     GpStatus status=Ok;
3524     GpBitmap *bitmap;
3525     HRESULT hr;
3526     IWICBitmapDecoder *decoder;
3527     IWICBitmapFrameDecode *frame;
3528     IWICBitmapSource *source=NULL;
3529     IWICMetadataBlockReader *block_reader;
3530     WICPixelFormatGUID wic_format;
3531     PixelFormat gdip_format=0;
3532     ColorPalette *palette = NULL;
3533     WICBitmapPaletteType palette_type = WICBitmapPaletteTypeFixedHalftone256;
3534     int i;
3535     UINT width, height, frame_count;
3536     BitmapData lockeddata;
3537     WICRect wrc;
3538     HRESULT initresult;
3539
3540     TRACE("%p,%s,%u,%p\n", stream, wine_dbgstr_guid(clsid), active_frame, image);
3541
3542     initresult = CoInitialize(NULL);
3543
3544     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
3545         &IID_IWICBitmapDecoder, (void**)&decoder);
3546     if (FAILED(hr)) goto end;
3547
3548     hr = IWICBitmapDecoder_Initialize(decoder, stream, WICDecodeMetadataCacheOnLoad);
3549     if (SUCCEEDED(hr))
3550     {
3551         IWICBitmapDecoder_GetFrameCount(decoder, &frame_count);
3552         hr = IWICBitmapDecoder_GetFrame(decoder, active_frame, &frame);
3553     }
3554
3555     if (SUCCEEDED(hr)) /* got frame */
3556     {
3557         hr = IWICBitmapFrameDecode_GetPixelFormat(frame, &wic_format);
3558
3559         if (SUCCEEDED(hr))
3560         {
3561             IWICBitmapSource *bmp_source;
3562             IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICBitmapSource, (void **)&bmp_source);
3563
3564             for (i=0; pixel_formats[i].wic_format; i++)
3565             {
3566                 if (IsEqualGUID(&wic_format, pixel_formats[i].wic_format))
3567                 {
3568                     source = bmp_source;
3569                     gdip_format = pixel_formats[i].gdip_format;
3570                     palette_type = pixel_formats[i].palette_type;
3571                     break;
3572                 }
3573             }
3574             if (!source)
3575             {
3576                 /* unknown format; fall back on 32bppARGB */
3577                 hr = WICConvertBitmapSource(&GUID_WICPixelFormat32bppBGRA, bmp_source, &source);
3578                 gdip_format = PixelFormat32bppARGB;
3579                 IWICBitmapSource_Release(bmp_source);
3580             }
3581             TRACE("%s => %#x\n", wine_dbgstr_guid(&wic_format), gdip_format);
3582         }
3583
3584         if (SUCCEEDED(hr)) /* got source */
3585         {
3586             hr = IWICBitmapSource_GetSize(source, &width, &height);
3587
3588             if (SUCCEEDED(hr))
3589                 status = GdipCreateBitmapFromScan0(width, height, 0, gdip_format,
3590                     NULL, &bitmap);
3591
3592             if (SUCCEEDED(hr) && status == Ok) /* created bitmap */
3593             {
3594                 status = GdipBitmapLockBits(bitmap, NULL, ImageLockModeWrite,
3595                     gdip_format, &lockeddata);
3596                 if (status == Ok) /* locked bitmap */
3597                 {
3598                     wrc.X = 0;
3599                     wrc.Width = width;
3600                     wrc.Height = 1;
3601                     for (i=0; i<height; i++)
3602                     {
3603                         wrc.Y = i;
3604                         hr = IWICBitmapSource_CopyPixels(source, &wrc, abs(lockeddata.Stride),
3605                             abs(lockeddata.Stride), (BYTE*)lockeddata.Scan0+lockeddata.Stride*i);
3606                         if (FAILED(hr)) break;
3607                     }
3608
3609                     GdipBitmapUnlockBits(bitmap, &lockeddata);
3610                 }
3611
3612                 if (SUCCEEDED(hr) && status == Ok)
3613                     *image = (GpImage*)bitmap;
3614                 else
3615                 {
3616                     *image = NULL;
3617                     GdipDisposeImage((GpImage*)bitmap);
3618                 }
3619
3620                 if (SUCCEEDED(hr) && status == Ok)
3621                 {
3622                     double dpix, dpiy;
3623                     hr = IWICBitmapSource_GetResolution(source, &dpix, &dpiy);
3624                     if (SUCCEEDED(hr))
3625                     {
3626                         bitmap->image.xres = dpix;
3627                         bitmap->image.yres = dpiy;
3628                     }
3629                     hr = S_OK;
3630                 }
3631             }
3632
3633             IWICBitmapSource_Release(source);
3634         }
3635
3636         if (SUCCEEDED(hr)) {
3637             bitmap->metadata_reader = NULL;
3638
3639             if (metadata_reader)
3640                 metadata_reader(bitmap, decoder, active_frame);
3641             else if (IWICBitmapFrameDecode_QueryInterface(frame, &IID_IWICMetadataBlockReader, (void **)&block_reader) == S_OK)
3642             {
3643                 UINT block_count = 0;
3644                 if (IWICMetadataBlockReader_GetCount(block_reader, &block_count) == S_OK && block_count)
3645                     IWICMetadataBlockReader_GetReaderByIndex(block_reader, 0, &bitmap->metadata_reader);
3646                 IWICMetadataBlockReader_Release(block_reader);
3647             }
3648
3649             palette = get_palette(frame, palette_type);
3650             IWICBitmapFrameDecode_Release(frame);
3651         }
3652     }
3653
3654     IWICBitmapDecoder_Release(decoder);
3655
3656 end:
3657     if (SUCCEEDED(initresult)) CoUninitialize();
3658
3659     if (FAILED(hr) && status == Ok) status = hresult_to_status(hr);
3660
3661     if (status == Ok)
3662     {
3663         /* Native GDI+ used to be smarter, but since Win7 it just sets these flags. */
3664         bitmap->image.flags |= ImageFlagsReadOnly|ImageFlagsHasRealPixelSize|ImageFlagsHasRealDPI|ImageFlagsColorSpaceRGB;
3665         bitmap->image.frame_count = frame_count;
3666         bitmap->image.current_frame = active_frame;
3667         bitmap->image.stream = stream;
3668         if (palette)
3669         {
3670             GdipFree(bitmap->image.palette);
3671             bitmap->image.palette = palette;
3672         }
3673         else
3674         {
3675             if (IsEqualGUID(&wic_format, &GUID_WICPixelFormatBlackWhite))
3676                 bitmap->image.palette->Flags = 0;
3677         }
3678         /* Pin the source stream */
3679         IStream_AddRef(stream);
3680         TRACE("=> %p\n", *image);
3681     }
3682
3683     return status;
3684 }
3685
3686 static GpStatus decode_image_icon(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3687 {
3688     return decode_image_wic(stream, &CLSID_WICIcoDecoder, active_frame, NULL, image);
3689 }
3690
3691 static GpStatus decode_image_bmp(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3692 {
3693     GpStatus status;
3694     GpBitmap* bitmap;
3695
3696     status = decode_image_wic(stream, &CLSID_WICBmpDecoder, active_frame, NULL, image);
3697
3698     bitmap = (GpBitmap*)*image;
3699
3700     if (status == Ok && bitmap->format == PixelFormat32bppARGB)
3701     {
3702         /* WIC supports bmp files with alpha, but gdiplus does not */
3703         bitmap->format = PixelFormat32bppRGB;
3704     }
3705
3706     return status;
3707 }
3708
3709 static GpStatus decode_image_jpeg(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3710 {
3711     return decode_image_wic(stream, &CLSID_WICJpegDecoder, active_frame, NULL, image);
3712 }
3713
3714 static GpStatus decode_image_png(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3715 {
3716     return decode_image_wic(stream, &CLSID_WICPngDecoder, active_frame, NULL, image);
3717 }
3718
3719 static GpStatus decode_image_gif(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3720 {
3721     return decode_image_wic(stream, &CLSID_WICGifDecoder, active_frame, gif_metadata_reader, image);
3722 }
3723
3724 static GpStatus decode_image_tiff(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3725 {
3726     return decode_image_wic(stream, &CLSID_WICTiffDecoder, active_frame, NULL, image);
3727 }
3728
3729 static GpStatus decode_image_olepicture_metafile(IStream* stream, REFCLSID clsid, UINT active_frame, GpImage **image)
3730 {
3731     IPicture *pic;
3732
3733     TRACE("%p %p\n", stream, image);
3734
3735     if(!stream || !image)
3736         return InvalidParameter;
3737
3738     if(OleLoadPicture(stream, 0, FALSE, &IID_IPicture,
3739         (LPVOID*) &pic) != S_OK){
3740         TRACE("Could not load picture\n");
3741         return GenericError;
3742     }
3743
3744     /* FIXME: missing initialization code */
3745     *image = GdipAlloc(sizeof(GpMetafile));
3746     if(!*image) return OutOfMemory;
3747     (*image)->type = ImageTypeMetafile;
3748     (*image)->stream = NULL;
3749     (*image)->picture = pic;
3750     (*image)->flags   = ImageFlagsNone;
3751     (*image)->frame_count = 1;
3752     (*image)->current_frame = 0;
3753     (*image)->palette = NULL;
3754
3755     TRACE("<-- %p\n", *image);
3756
3757     return Ok;
3758 }
3759
3760 typedef GpStatus (*encode_image_func)(GpImage *image, IStream* stream,
3761     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params);
3762
3763 typedef GpStatus (*decode_image_func)(IStream *stream, REFCLSID clsid, UINT active_frame, GpImage **image);
3764
3765 typedef struct image_codec {
3766     ImageCodecInfo info;
3767     encode_image_func encode_func;
3768     decode_image_func decode_func;
3769 } image_codec;
3770
3771 typedef enum {
3772     BMP,
3773     JPEG,
3774     GIF,
3775     TIFF,
3776     EMF,
3777     WMF,
3778     PNG,
3779     ICO,
3780     NUM_CODECS
3781 } ImageFormat;
3782
3783 static const struct image_codec codecs[NUM_CODECS];
3784
3785 static GpStatus get_decoder_info(IStream* stream, const struct image_codec **result)
3786 {
3787     BYTE signature[8];
3788     const BYTE *pattern, *mask;
3789     LARGE_INTEGER seek;
3790     HRESULT hr;
3791     UINT bytesread;
3792     int i;
3793     DWORD j, sig;
3794
3795     /* seek to the start of the stream */
3796     seek.QuadPart = 0;
3797     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3798     if (FAILED(hr)) return hresult_to_status(hr);
3799
3800     /* read the first 8 bytes */
3801     /* FIXME: This assumes all codecs have signatures <= 8 bytes in length */
3802     hr = IStream_Read(stream, signature, 8, &bytesread);
3803     if (FAILED(hr)) return hresult_to_status(hr);
3804     if (hr == S_FALSE || bytesread == 0) return GenericError;
3805
3806     for (i = 0; i < NUM_CODECS; i++) {
3807         if ((codecs[i].info.Flags & ImageCodecFlagsDecoder) &&
3808             bytesread >= codecs[i].info.SigSize)
3809         {
3810             for (sig=0; sig<codecs[i].info.SigCount; sig++)
3811             {
3812                 pattern = &codecs[i].info.SigPattern[codecs[i].info.SigSize*sig];
3813                 mask = &codecs[i].info.SigMask[codecs[i].info.SigSize*sig];
3814                 for (j=0; j<codecs[i].info.SigSize; j++)
3815                     if ((signature[j] & mask[j]) != pattern[j])
3816                         break;
3817                 if (j == codecs[i].info.SigSize)
3818                 {
3819                     *result = &codecs[i];
3820                     return Ok;
3821                 }
3822             }
3823         }
3824     }
3825
3826     TRACE("no match for %i byte signature %x %x %x %x %x %x %x %x\n", bytesread,
3827         signature[0],signature[1],signature[2],signature[3],
3828         signature[4],signature[5],signature[6],signature[7]);
3829
3830     return GenericError;
3831 }
3832
3833 GpStatus WINGDIPAPI GdipImageSelectActiveFrame(GpImage *image, GDIPCONST GUID *dimensionID,
3834                                                UINT frame)
3835 {
3836     GpStatus stat;
3837     LARGE_INTEGER seek;
3838     HRESULT hr;
3839     const struct image_codec *codec = NULL;
3840     GpImage *new_image;
3841
3842     TRACE("(%p,%s,%u)\n", image, debugstr_guid(dimensionID), frame);
3843
3844     if (!image || !dimensionID)
3845         return InvalidParameter;
3846
3847     if (frame >= image->frame_count)
3848     {
3849         WARN("requested frame %u, but image has only %u\n", frame, image->frame_count);
3850         return InvalidParameter;
3851     }
3852
3853     if (image->type != ImageTypeBitmap && image->type != ImageTypeMetafile)
3854     {
3855         WARN("invalid image type %d\n", image->type);
3856         return InvalidParameter;
3857     }
3858
3859     if (image->current_frame == frame)
3860         return Ok;
3861
3862     if (!image->stream)
3863     {
3864         TRACE("image doesn't have an associated stream\n");
3865         return Ok;
3866     }
3867
3868     /* choose an appropriate image decoder */
3869     stat = get_decoder_info(image->stream, &codec);
3870     if (stat != Ok)
3871     {
3872         WARN("can't find decoder info\n");
3873         return stat;
3874     }
3875
3876     /* seek to the start of the stream */
3877     seek.QuadPart = 0;
3878     hr = IStream_Seek(image->stream, seek, STREAM_SEEK_SET, NULL);
3879     if (FAILED(hr))
3880         return hresult_to_status(hr);
3881
3882     /* call on the image decoder to do the real work */
3883     stat = codec->decode_func(image->stream, &codec->info.Clsid, frame, &new_image);
3884
3885     if (stat == Ok)
3886     {
3887         memcpy(&new_image->format, &codec->info.FormatID, sizeof(GUID));
3888         free_image_data(image);
3889         if (image->type == ImageTypeBitmap)
3890             *(GpBitmap *)image = *(GpBitmap *)new_image;
3891         else if (image->type == ImageTypeMetafile)
3892             *(GpMetafile *)image = *(GpMetafile *)new_image;
3893         new_image->type = ~0;
3894         GdipFree(new_image);
3895         return Ok;
3896     }
3897
3898     return stat;
3899 }
3900
3901 GpStatus WINGDIPAPI GdipLoadImageFromStream(IStream *stream, GpImage **image)
3902 {
3903     GpStatus stat;
3904     LARGE_INTEGER seek;
3905     HRESULT hr;
3906     const struct image_codec *codec=NULL;
3907
3908     /* choose an appropriate image decoder */
3909     stat = get_decoder_info(stream, &codec);
3910     if (stat != Ok) return stat;
3911
3912     /* seek to the start of the stream */
3913     seek.QuadPart = 0;
3914     hr = IStream_Seek(stream, seek, STREAM_SEEK_SET, NULL);
3915     if (FAILED(hr)) return hresult_to_status(hr);
3916
3917     /* call on the image decoder to do the real work */
3918     stat = codec->decode_func(stream, &codec->info.Clsid, 0, image);
3919
3920     /* take note of the original data format */
3921     if (stat == Ok)
3922     {
3923         memcpy(&(*image)->format, &codec->info.FormatID, sizeof(GUID));
3924         return Ok;
3925     }
3926
3927     return stat;
3928 }
3929
3930 /* FIXME: no ICM */
3931 GpStatus WINGDIPAPI GdipLoadImageFromStreamICM(IStream* stream, GpImage **image)
3932 {
3933     TRACE("%p %p\n", stream, image);
3934
3935     return GdipLoadImageFromStream(stream, image);
3936 }
3937
3938 GpStatus WINGDIPAPI GdipRemovePropertyItem(GpImage *image, PROPID propId)
3939 {
3940     static int calls;
3941
3942     TRACE("(%p,%u)\n", image, propId);
3943
3944     if(!image)
3945         return InvalidParameter;
3946
3947     if(!(calls++))
3948         FIXME("not implemented\n");
3949
3950     return NotImplemented;
3951 }
3952
3953 GpStatus WINGDIPAPI GdipSetPropertyItem(GpImage *image, GDIPCONST PropertyItem* item)
3954 {
3955     static int calls;
3956
3957     if (!image || !item) return InvalidParameter;
3958
3959     TRACE("(%p,%p:%#x,%u,%u,%p)\n", image, item, item->id, item->type, item->length, item->value);
3960
3961     if(!(calls++))
3962         FIXME("not implemented\n");
3963
3964     return Ok;
3965 }
3966
3967 GpStatus WINGDIPAPI GdipSaveImageToFile(GpImage *image, GDIPCONST WCHAR* filename,
3968                                         GDIPCONST CLSID *clsidEncoder,
3969                                         GDIPCONST EncoderParameters *encoderParams)
3970 {
3971     GpStatus stat;
3972     IStream *stream;
3973
3974     TRACE("%p (%s) %p %p\n", image, debugstr_w(filename), clsidEncoder, encoderParams);
3975
3976     if (!image || !filename|| !clsidEncoder)
3977         return InvalidParameter;
3978
3979     stat = GdipCreateStreamOnFile(filename, GENERIC_WRITE, &stream);
3980     if (stat != Ok)
3981         return GenericError;
3982
3983     stat = GdipSaveImageToStream(image, stream, clsidEncoder, encoderParams);
3984
3985     IStream_Release(stream);
3986     return stat;
3987 }
3988
3989 /*************************************************************************
3990  * Encoding functions -
3991  *   These functions encode an image in different image file formats.
3992  */
3993 #define BITMAP_FORMAT_BMP   0x4d42 /* "BM" */
3994 #define BITMAP_FORMAT_JPEG  0xd8ff
3995 #define BITMAP_FORMAT_GIF   0x4947
3996 #define BITMAP_FORMAT_PNG   0x5089
3997 #define BITMAP_FORMAT_APM   0xcdd7
3998
3999 static GpStatus encode_image_WIC(GpImage *image, IStream* stream,
4000     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4001 {
4002     GpStatus stat;
4003     GpBitmap *bitmap;
4004     IWICBitmapEncoder *encoder;
4005     IWICBitmapFrameEncode *frameencode;
4006     IPropertyBag2 *encoderoptions;
4007     HRESULT hr;
4008     UINT width, height;
4009     PixelFormat gdipformat=0;
4010     WICPixelFormatGUID wicformat;
4011     GpRect rc;
4012     BitmapData lockeddata;
4013     HRESULT initresult;
4014     UINT i;
4015
4016     if (image->type != ImageTypeBitmap)
4017         return GenericError;
4018
4019     bitmap = (GpBitmap*)image;
4020
4021     GdipGetImageWidth(image, &width);
4022     GdipGetImageHeight(image, &height);
4023
4024     rc.X = 0;
4025     rc.Y = 0;
4026     rc.Width = width;
4027     rc.Height = height;
4028
4029     initresult = CoInitialize(NULL);
4030
4031     hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
4032         &IID_IWICBitmapEncoder, (void**)&encoder);
4033     if (FAILED(hr))
4034     {
4035         if (SUCCEEDED(initresult)) CoUninitialize();
4036         return hresult_to_status(hr);
4037     }
4038
4039     hr = IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache);
4040
4041     if (SUCCEEDED(hr))
4042     {
4043         hr = IWICBitmapEncoder_CreateNewFrame(encoder, &frameencode, &encoderoptions);
4044     }
4045
4046     if (SUCCEEDED(hr)) /* created frame */
4047     {
4048         hr = IWICBitmapFrameEncode_Initialize(frameencode, encoderoptions);
4049
4050         if (SUCCEEDED(hr))
4051             hr = IWICBitmapFrameEncode_SetSize(frameencode, width, height);
4052
4053         if (SUCCEEDED(hr))
4054             hr = IWICBitmapFrameEncode_SetResolution(frameencode, image->xres, image->yres);
4055
4056         if (SUCCEEDED(hr))
4057         {
4058             for (i=0; pixel_formats[i].wic_format; i++)
4059             {
4060                 if (pixel_formats[i].gdip_format == bitmap->format)
4061                 {
4062                     memcpy(&wicformat, pixel_formats[i].wic_format, sizeof(GUID));
4063                     gdipformat = bitmap->format;
4064                     break;
4065                 }
4066             }
4067             if (!gdipformat)
4068             {
4069                 memcpy(&wicformat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
4070                 gdipformat = PixelFormat32bppARGB;
4071             }
4072
4073             hr = IWICBitmapFrameEncode_SetPixelFormat(frameencode, &wicformat);
4074         }
4075
4076         if (SUCCEEDED(hr))
4077         {
4078             stat = GdipBitmapLockBits(bitmap, &rc, ImageLockModeRead, gdipformat,
4079                 &lockeddata);
4080
4081             if (stat == Ok)
4082             {
4083                 UINT row_size = (lockeddata.Width * PIXELFORMATBPP(gdipformat) + 7)/8;
4084                 BYTE *row;
4085
4086                 /* write one row at a time in case stride is negative */
4087                 row = lockeddata.Scan0;
4088                 for (i=0; i<lockeddata.Height; i++)
4089                 {
4090                     hr = IWICBitmapFrameEncode_WritePixels(frameencode, 1, row_size, row_size, row);
4091                     if (FAILED(hr)) break;
4092                     row += lockeddata.Stride;
4093                 }
4094
4095                 GdipBitmapUnlockBits(bitmap, &lockeddata);
4096             }
4097             else
4098                 hr = E_FAIL;
4099         }
4100
4101         if (SUCCEEDED(hr))
4102             hr = IWICBitmapFrameEncode_Commit(frameencode);
4103
4104         IWICBitmapFrameEncode_Release(frameencode);
4105         IPropertyBag2_Release(encoderoptions);
4106     }
4107
4108     if (SUCCEEDED(hr))
4109         hr = IWICBitmapEncoder_Commit(encoder);
4110
4111     IWICBitmapEncoder_Release(encoder);
4112
4113     if (SUCCEEDED(initresult)) CoUninitialize();
4114
4115     return hresult_to_status(hr);
4116 }
4117
4118 static GpStatus encode_image_BMP(GpImage *image, IStream* stream,
4119     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4120 {
4121     return encode_image_WIC(image, stream, &CLSID_WICBmpEncoder, params);
4122 }
4123
4124 static GpStatus encode_image_tiff(GpImage *image, IStream* stream,
4125     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4126 {
4127     return encode_image_WIC(image, stream, &CLSID_WICTiffEncoder, params);
4128 }
4129
4130 static GpStatus encode_image_png(GpImage *image, IStream* stream,
4131     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4132 {
4133     return encode_image_WIC(image, stream, &CLSID_WICPngEncoder, params);
4134 }
4135
4136 static GpStatus encode_image_jpeg(GpImage *image, IStream* stream,
4137     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4138 {
4139     return encode_image_WIC(image, stream, &CLSID_WICJpegEncoder, params);
4140 }
4141
4142 /*****************************************************************************
4143  * GdipSaveImageToStream [GDIPLUS.@]
4144  */
4145 GpStatus WINGDIPAPI GdipSaveImageToStream(GpImage *image, IStream* stream,
4146     GDIPCONST CLSID* clsid, GDIPCONST EncoderParameters* params)
4147 {
4148     GpStatus stat;
4149     encode_image_func encode_image;
4150     int i;
4151
4152     TRACE("%p %p %p %p\n", image, stream, clsid, params);
4153
4154     if(!image || !stream)
4155         return InvalidParameter;
4156
4157     /* select correct encoder */
4158     encode_image = NULL;
4159     for (i = 0; i < NUM_CODECS; i++) {
4160         if ((codecs[i].info.Flags & ImageCodecFlagsEncoder) &&
4161             IsEqualCLSID(clsid, &codecs[i].info.Clsid))
4162             encode_image = codecs[i].encode_func;
4163     }
4164     if (encode_image == NULL)
4165         return UnknownImageFormat;
4166
4167     stat = encode_image(image, stream, clsid, params);
4168
4169     return stat;
4170 }
4171
4172 /*****************************************************************************
4173  * GdipSaveAdd [GDIPLUS.@]
4174  */
4175 GpStatus WINGDIPAPI GdipSaveAdd(GpImage *image, GDIPCONST EncoderParameters *params)
4176 {
4177     FIXME("(%p,%p): stub\n", image, params);
4178     return Ok;
4179 }
4180
4181 /*****************************************************************************
4182  * GdipGetImagePalette [GDIPLUS.@]
4183  */
4184 GpStatus WINGDIPAPI GdipGetImagePalette(GpImage *image, ColorPalette *palette, INT size)
4185 {
4186     INT count;
4187
4188     TRACE("(%p,%p,%i)\n", image, palette, size);
4189
4190     if (!image || !palette)
4191         return InvalidParameter;
4192
4193     count = image->palette ? image->palette->Count : 0;
4194
4195     if (size < (sizeof(UINT)*2+sizeof(ARGB)*count))
4196     {
4197         TRACE("<-- InsufficientBuffer\n");
4198         return InsufficientBuffer;
4199     }
4200
4201     if (image->palette)
4202     {
4203         palette->Flags = image->palette->Flags;
4204         palette->Count = image->palette->Count;
4205         memcpy(palette->Entries, image->palette->Entries, sizeof(ARGB)*image->palette->Count);
4206     }
4207     else
4208     {
4209         palette->Flags = 0;
4210         palette->Count = 0;
4211     }
4212     return Ok;
4213 }
4214
4215 /*****************************************************************************
4216  * GdipSetImagePalette [GDIPLUS.@]
4217  */
4218 GpStatus WINGDIPAPI GdipSetImagePalette(GpImage *image,
4219     GDIPCONST ColorPalette *palette)
4220 {
4221     ColorPalette *new_palette;
4222
4223     TRACE("(%p,%p)\n", image, palette);
4224
4225     if(!image || !palette || palette->Count > 256)
4226         return InvalidParameter;
4227
4228     new_palette = GdipAlloc(2 * sizeof(UINT) + palette->Count * sizeof(ARGB));
4229     if (!new_palette) return OutOfMemory;
4230
4231     GdipFree(image->palette);
4232     image->palette = new_palette;
4233     image->palette->Flags = palette->Flags;
4234     image->palette->Count = palette->Count;
4235     memcpy(image->palette->Entries, palette->Entries, sizeof(ARGB)*palette->Count);
4236
4237     return Ok;
4238 }
4239
4240 /*************************************************************************
4241  * Encoders -
4242  *   Structures that represent which formats we support for encoding.
4243  */
4244
4245 /* ImageCodecInfo creation routines taken from libgdiplus */
4246 static const WCHAR bmp_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'B', 'M', 'P', 0}; /* Built-in BMP */
4247 static const WCHAR bmp_extension[] = {'*','.','B', 'M', 'P',';', '*','.', 'D','I', 'B',';', '*','.', 'R', 'L', 'E',0}; /* *.BMP;*.DIB;*.RLE */
4248 static const WCHAR bmp_mimetype[] = {'i', 'm', 'a','g', 'e', '/', 'b', 'm', 'p', 0}; /* image/bmp */
4249 static const WCHAR bmp_format[] = {'B', 'M', 'P', 0}; /* BMP */
4250 static const BYTE bmp_sig_pattern[] = { 0x42, 0x4D };
4251 static const BYTE bmp_sig_mask[] = { 0xFF, 0xFF };
4252
4253 static const WCHAR jpeg_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'J','P','E','G', 0};
4254 static const WCHAR jpeg_extension[] = {'*','.','J','P','G',';', '*','.','J','P','E','G',';', '*','.','J','P','E',';', '*','.','J','F','I','F',0};
4255 static const WCHAR jpeg_mimetype[] = {'i','m','a','g','e','/','j','p','e','g', 0};
4256 static const WCHAR jpeg_format[] = {'J','P','E','G',0};
4257 static const BYTE jpeg_sig_pattern[] = { 0xFF, 0xD8 };
4258 static const BYTE jpeg_sig_mask[] = { 0xFF, 0xFF };
4259
4260 static const WCHAR gif_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'G','I','F', 0};
4261 static const WCHAR gif_extension[] = {'*','.','G','I','F',0};
4262 static const WCHAR gif_mimetype[] = {'i','m','a','g','e','/','g','i','f', 0};
4263 static const WCHAR gif_format[] = {'G','I','F',0};
4264 static const BYTE gif_sig_pattern[12] = "GIF87aGIF89a";
4265 static const BYTE gif_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4266
4267 static const WCHAR tiff_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'T','I','F','F', 0};
4268 static const WCHAR tiff_extension[] = {'*','.','T','I','F','F',';','*','.','T','I','F',0};
4269 static const WCHAR tiff_mimetype[] = {'i','m','a','g','e','/','t','i','f','f', 0};
4270 static const WCHAR tiff_format[] = {'T','I','F','F',0};
4271 static const BYTE tiff_sig_pattern[] = {0x49,0x49,42,0,0x4d,0x4d,0,42};
4272 static const BYTE tiff_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4273
4274 static const WCHAR emf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'E','M','F', 0};
4275 static const WCHAR emf_extension[] = {'*','.','E','M','F',0};
4276 static const WCHAR emf_mimetype[] = {'i','m','a','g','e','/','x','-','e','m','f', 0};
4277 static const WCHAR emf_format[] = {'E','M','F',0};
4278 static const BYTE emf_sig_pattern[] = { 0x01, 0x00, 0x00, 0x00 };
4279 static const BYTE emf_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4280
4281 static const WCHAR wmf_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'W','M','F', 0};
4282 static const WCHAR wmf_extension[] = {'*','.','W','M','F',0};
4283 static const WCHAR wmf_mimetype[] = {'i','m','a','g','e','/','x','-','w','m','f', 0};
4284 static const WCHAR wmf_format[] = {'W','M','F',0};
4285 static const BYTE wmf_sig_pattern[] = { 0xd7, 0xcd };
4286 static const BYTE wmf_sig_mask[] = { 0xFF, 0xFF };
4287
4288 static const WCHAR png_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'P','N','G', 0};
4289 static const WCHAR png_extension[] = {'*','.','P','N','G',0};
4290 static const WCHAR png_mimetype[] = {'i','m','a','g','e','/','p','n','g', 0};
4291 static const WCHAR png_format[] = {'P','N','G',0};
4292 static const BYTE png_sig_pattern[] = { 137, 80, 78, 71, 13, 10, 26, 10, };
4293 static const BYTE png_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
4294
4295 static const WCHAR ico_codecname[] = {'B', 'u', 'i','l', 't', '-','i', 'n', ' ', 'I','C','O', 0};
4296 static const WCHAR ico_extension[] = {'*','.','I','C','O',0};
4297 static const WCHAR ico_mimetype[] = {'i','m','a','g','e','/','x','-','i','c','o','n', 0};
4298 static const WCHAR ico_format[] = {'I','C','O',0};
4299 static const BYTE ico_sig_pattern[] = { 0x00, 0x00, 0x01, 0x00 };
4300 static const BYTE ico_sig_mask[] = { 0xFF, 0xFF, 0xFF, 0xFF };
4301
4302 static const struct image_codec codecs[NUM_CODECS] = {
4303     {
4304         { /* BMP */
4305             /* Clsid */              { 0x557cf400, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4306             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4307             /* CodecName */          bmp_codecname,
4308             /* DllName */            NULL,
4309             /* FormatDescription */  bmp_format,
4310             /* FilenameExtension */  bmp_extension,
4311             /* MimeType */           bmp_mimetype,
4312             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4313             /* Version */            1,
4314             /* SigCount */           1,
4315             /* SigSize */            2,
4316             /* SigPattern */         bmp_sig_pattern,
4317             /* SigMask */            bmp_sig_mask,
4318         },
4319         encode_image_BMP,
4320         decode_image_bmp
4321     },
4322     {
4323         { /* JPEG */
4324             /* Clsid */              { 0x557cf401, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4325             /* FormatID */           { 0xb96b3caeU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4326             /* CodecName */          jpeg_codecname,
4327             /* DllName */            NULL,
4328             /* FormatDescription */  jpeg_format,
4329             /* FilenameExtension */  jpeg_extension,
4330             /* MimeType */           jpeg_mimetype,
4331             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4332             /* Version */            1,
4333             /* SigCount */           1,
4334             /* SigSize */            2,
4335             /* SigPattern */         jpeg_sig_pattern,
4336             /* SigMask */            jpeg_sig_mask,
4337         },
4338         encode_image_jpeg,
4339         decode_image_jpeg
4340     },
4341     {
4342         { /* GIF */
4343             /* Clsid */              { 0x557cf402, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4344             /* FormatID */           { 0xb96b3cb0U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4345             /* CodecName */          gif_codecname,
4346             /* DllName */            NULL,
4347             /* FormatDescription */  gif_format,
4348             /* FilenameExtension */  gif_extension,
4349             /* MimeType */           gif_mimetype,
4350             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4351             /* Version */            1,
4352             /* SigCount */           2,
4353             /* SigSize */            6,
4354             /* SigPattern */         gif_sig_pattern,
4355             /* SigMask */            gif_sig_mask,
4356         },
4357         NULL,
4358         decode_image_gif
4359     },
4360     {
4361         { /* TIFF */
4362             /* Clsid */              { 0x557cf405, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4363             /* FormatID */           { 0xb96b3cb1U, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4364             /* CodecName */          tiff_codecname,
4365             /* DllName */            NULL,
4366             /* FormatDescription */  tiff_format,
4367             /* FilenameExtension */  tiff_extension,
4368             /* MimeType */           tiff_mimetype,
4369             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsEncoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4370             /* Version */            1,
4371             /* SigCount */           2,
4372             /* SigSize */            4,
4373             /* SigPattern */         tiff_sig_pattern,
4374             /* SigMask */            tiff_sig_mask,
4375         },
4376         encode_image_tiff,
4377         decode_image_tiff
4378     },
4379     {
4380         { /* EMF */
4381             /* Clsid */              { 0x557cf403, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4382             /* FormatID */           { 0xb96b3cacU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4383             /* CodecName */          emf_codecname,
4384             /* DllName */            NULL,
4385             /* FormatDescription */  emf_format,
4386             /* FilenameExtension */  emf_extension,
4387             /* MimeType */           emf_mimetype,
4388             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4389             /* Version */            1,
4390             /* SigCount */           1,
4391             /* SigSize */            4,
4392             /* SigPattern */         emf_sig_pattern,
4393             /* SigMask */            emf_sig_mask,
4394         },
4395         NULL,
4396         decode_image_olepicture_metafile
4397     },
4398     {
4399         { /* WMF */
4400             /* Clsid */              { 0x557cf404, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4401             /* FormatID */           { 0xb96b3cadU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4402             /* CodecName */          wmf_codecname,
4403             /* DllName */            NULL,
4404             /* FormatDescription */  wmf_format,
4405             /* FilenameExtension */  wmf_extension,
4406             /* MimeType */           wmf_mimetype,
4407             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportVector | ImageCodecFlagsBuiltin,
4408             /* Version */            1,
4409             /* SigCount */           1,
4410             /* SigSize */            2,
4411             /* SigPattern */         wmf_sig_pattern,
4412             /* SigMask */            wmf_sig_mask,
4413         },
4414         NULL,
4415         decode_image_olepicture_metafile
4416     },
4417     {
4418         { /* PNG */
4419             /* Clsid */              { 0x557cf406, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4420             /* FormatID */           { 0xb96b3cafU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4421             /* CodecName */          png_codecname,
4422             /* DllName */            NULL,
4423             /* FormatDescription */  png_format,
4424             /* FilenameExtension */  png_extension,
4425             /* MimeType */           png_mimetype,
4426             /* Flags */              ImageCodecFlagsEncoder | ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4427             /* Version */            1,
4428             /* SigCount */           1,
4429             /* SigSize */            8,
4430             /* SigPattern */         png_sig_pattern,
4431             /* SigMask */            png_sig_mask,
4432         },
4433         encode_image_png,
4434         decode_image_png
4435     },
4436     {
4437         { /* ICO */
4438             /* Clsid */              { 0x557cf407, 0x1a04, 0x11d3, { 0x9a, 0x73, 0x0, 0x0, 0xf8, 0x1e, 0xf3, 0x2e } },
4439             /* FormatID */           { 0xb96b3cabU, 0x0728U, 0x11d3U, {0x9d, 0x7b, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e} },
4440             /* CodecName */          ico_codecname,
4441             /* DllName */            NULL,
4442             /* FormatDescription */  ico_format,
4443             /* FilenameExtension */  ico_extension,
4444             /* MimeType */           ico_mimetype,
4445             /* Flags */              ImageCodecFlagsDecoder | ImageCodecFlagsSupportBitmap | ImageCodecFlagsBuiltin,
4446             /* Version */            1,
4447             /* SigCount */           1,
4448             /* SigSize */            4,
4449             /* SigPattern */         ico_sig_pattern,
4450             /* SigMask */            ico_sig_mask,
4451         },
4452         NULL,
4453         decode_image_icon
4454     },
4455 };
4456
4457 /*****************************************************************************
4458  * GdipGetImageDecodersSize [GDIPLUS.@]
4459  */
4460 GpStatus WINGDIPAPI GdipGetImageDecodersSize(UINT *numDecoders, UINT *size)
4461 {
4462     int decoder_count=0;
4463     int i;
4464     TRACE("%p %p\n", numDecoders, size);
4465
4466     if (!numDecoders || !size)
4467         return InvalidParameter;
4468
4469     for (i=0; i<NUM_CODECS; i++)
4470     {
4471         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4472             decoder_count++;
4473     }
4474
4475     *numDecoders = decoder_count;
4476     *size = decoder_count * sizeof(ImageCodecInfo);
4477
4478     return Ok;
4479 }
4480
4481 /*****************************************************************************
4482  * GdipGetImageDecoders [GDIPLUS.@]
4483  */
4484 GpStatus WINGDIPAPI GdipGetImageDecoders(UINT numDecoders, UINT size, ImageCodecInfo *decoders)
4485 {
4486     int i, decoder_count=0;
4487     TRACE("%u %u %p\n", numDecoders, size, decoders);
4488
4489     if (!decoders ||
4490         size != numDecoders * sizeof(ImageCodecInfo))
4491         return GenericError;
4492
4493     for (i=0; i<NUM_CODECS; i++)
4494     {
4495         if (codecs[i].info.Flags & ImageCodecFlagsDecoder)
4496         {
4497             if (decoder_count == numDecoders) return GenericError;
4498             memcpy(&decoders[decoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4499             decoder_count++;
4500         }
4501     }
4502
4503     if (decoder_count < numDecoders) return GenericError;
4504
4505     return Ok;
4506 }
4507
4508 /*****************************************************************************
4509  * GdipGetImageEncodersSize [GDIPLUS.@]
4510  */
4511 GpStatus WINGDIPAPI GdipGetImageEncodersSize(UINT *numEncoders, UINT *size)
4512 {
4513     int encoder_count=0;
4514     int i;
4515     TRACE("%p %p\n", numEncoders, size);
4516
4517     if (!numEncoders || !size)
4518         return InvalidParameter;
4519
4520     for (i=0; i<NUM_CODECS; i++)
4521     {
4522         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4523             encoder_count++;
4524     }
4525
4526     *numEncoders = encoder_count;
4527     *size = encoder_count * sizeof(ImageCodecInfo);
4528
4529     return Ok;
4530 }
4531
4532 /*****************************************************************************
4533  * GdipGetImageEncoders [GDIPLUS.@]
4534  */
4535 GpStatus WINGDIPAPI GdipGetImageEncoders(UINT numEncoders, UINT size, ImageCodecInfo *encoders)
4536 {
4537     int i, encoder_count=0;
4538     TRACE("%u %u %p\n", numEncoders, size, encoders);
4539
4540     if (!encoders ||
4541         size != numEncoders * sizeof(ImageCodecInfo))
4542         return GenericError;
4543
4544     for (i=0; i<NUM_CODECS; i++)
4545     {
4546         if (codecs[i].info.Flags & ImageCodecFlagsEncoder)
4547         {
4548             if (encoder_count == numEncoders) return GenericError;
4549             memcpy(&encoders[encoder_count], &codecs[i].info, sizeof(ImageCodecInfo));
4550             encoder_count++;
4551         }
4552     }
4553
4554     if (encoder_count < numEncoders) return GenericError;
4555
4556     return Ok;
4557 }
4558
4559 GpStatus WINGDIPAPI GdipGetEncoderParameterListSize(GpImage *image,
4560     GDIPCONST CLSID* clsidEncoder, UINT *size)
4561 {
4562     static int calls;
4563
4564     TRACE("(%p,%s,%p)\n", image, debugstr_guid(clsidEncoder), size);
4565
4566     if(!(calls++))
4567         FIXME("not implemented\n");
4568
4569     *size = 0;
4570
4571     return NotImplemented;
4572 }
4573
4574 static PixelFormat get_16bpp_format(HBITMAP hbm)
4575 {
4576     BITMAPV4HEADER bmh;
4577     HDC hdc;
4578     PixelFormat result;
4579
4580     hdc = CreateCompatibleDC(NULL);
4581
4582     memset(&bmh, 0, sizeof(bmh));
4583     bmh.bV4Size = sizeof(bmh);
4584     bmh.bV4Width = 1;
4585     bmh.bV4Height = 1;
4586     bmh.bV4V4Compression = BI_BITFIELDS;
4587     bmh.bV4BitCount = 16;
4588
4589     GetDIBits(hdc, hbm, 0, 0, NULL, (BITMAPINFO*)&bmh, DIB_RGB_COLORS);
4590
4591     if (bmh.bV4RedMask == 0x7c00 &&
4592         bmh.bV4GreenMask == 0x3e0 &&
4593         bmh.bV4BlueMask == 0x1f)
4594     {
4595         result = PixelFormat16bppRGB555;
4596     }
4597     else if (bmh.bV4RedMask == 0xf800 &&
4598         bmh.bV4GreenMask == 0x7e0 &&
4599         bmh.bV4BlueMask == 0x1f)
4600     {
4601         result = PixelFormat16bppRGB565;
4602     }
4603     else
4604     {
4605         FIXME("unrecognized bitfields %x,%x,%x\n", bmh.bV4RedMask,
4606             bmh.bV4GreenMask, bmh.bV4BlueMask);
4607         result = PixelFormatUndefined;
4608     }
4609
4610     DeleteDC(hdc);
4611
4612     return result;
4613 }
4614
4615 /*****************************************************************************
4616  * GdipCreateBitmapFromHBITMAP [GDIPLUS.@]
4617  */
4618 GpStatus WINGDIPAPI GdipCreateBitmapFromHBITMAP(HBITMAP hbm, HPALETTE hpal, GpBitmap** bitmap)
4619 {
4620     BITMAP bm;
4621     GpStatus retval;
4622     PixelFormat format;
4623     BitmapData lockeddata;
4624
4625     TRACE("%p %p %p\n", hbm, hpal, bitmap);
4626
4627     if(!hbm || !bitmap)
4628         return InvalidParameter;
4629
4630     if (GetObjectA(hbm, sizeof(bm), &bm) != sizeof(bm))
4631             return InvalidParameter;
4632
4633     /* TODO: Figure out the correct format for 16, 32, 64 bpp */
4634     switch(bm.bmBitsPixel) {
4635         case 1:
4636             format = PixelFormat1bppIndexed;
4637             break;
4638         case 4:
4639             format = PixelFormat4bppIndexed;
4640             break;
4641         case 8:
4642             format = PixelFormat8bppIndexed;
4643             break;
4644         case 16:
4645             format = get_16bpp_format(hbm);
4646             if (format == PixelFormatUndefined)
4647                 return InvalidParameter;
4648             break;
4649         case 24:
4650             format = PixelFormat24bppRGB;
4651             break;
4652         case 32:
4653             format = PixelFormat32bppRGB;
4654             break;
4655         case 48:
4656             format = PixelFormat48bppRGB;
4657             break;
4658         default:
4659             FIXME("don't know how to handle %d bpp\n", bm.bmBitsPixel);
4660             return InvalidParameter;
4661     }
4662
4663     retval = GdipCreateBitmapFromScan0(bm.bmWidth, bm.bmHeight, 0,
4664         format, NULL, bitmap);
4665
4666     if (retval == Ok)
4667     {
4668         retval = GdipBitmapLockBits(*bitmap, NULL, ImageLockModeWrite,
4669             format, &lockeddata);
4670         if (retval == Ok)
4671         {
4672             HDC hdc;
4673             char bmibuf[FIELD_OFFSET(BITMAPINFO, bmiColors[256])];
4674             BITMAPINFO *pbmi = (BITMAPINFO *)bmibuf;
4675             INT src_height;
4676
4677             hdc = CreateCompatibleDC(NULL);
4678
4679             pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
4680             pbmi->bmiHeader.biBitCount = 0;
4681
4682             GetDIBits(hdc, hbm, 0, 0, NULL, pbmi, DIB_RGB_COLORS);
4683
4684             src_height = abs(pbmi->bmiHeader.biHeight);
4685             pbmi->bmiHeader.biHeight = -src_height;
4686
4687             GetDIBits(hdc, hbm, 0, src_height, lockeddata.Scan0, pbmi, DIB_RGB_COLORS);
4688
4689             DeleteDC(hdc);
4690
4691             GdipBitmapUnlockBits(*bitmap, &lockeddata);
4692         }
4693
4694         if (retval == Ok && hpal)
4695         {
4696             PALETTEENTRY entry[256];
4697             ColorPalette *palette=NULL;
4698             int i, num_palette_entries;
4699
4700             num_palette_entries = GetPaletteEntries(hpal, 0, 256, entry);
4701             if (!num_palette_entries)
4702                 retval = GenericError;
4703
4704             palette = GdipAlloc(sizeof(ColorPalette) + sizeof(ARGB) * (num_palette_entries-1));
4705             if (!palette)
4706                 retval = OutOfMemory;
4707
4708             if (retval == Ok)
4709             {
4710                 palette->Flags = 0;
4711                 palette->Count = num_palette_entries;
4712
4713                 for (i=0; i<num_palette_entries; i++)
4714                 {
4715                     palette->Entries[i] = 0xff000000 | entry[i].peRed << 16 |
4716                                           entry[i].peGreen << 8 | entry[i].peBlue;
4717                 }
4718
4719                 retval = GdipSetImagePalette((GpImage*)*bitmap, palette);
4720             }
4721
4722             GdipFree(palette);
4723         }
4724
4725         if (retval != Ok)
4726         {
4727             GdipDisposeImage((GpImage*)*bitmap);
4728             *bitmap = NULL;
4729         }
4730     }
4731
4732     return retval;
4733 }
4734
4735 GpStatus WINGDIPAPI GdipDeleteEffect(CGpEffect *effect)
4736 {
4737     FIXME("(%p): stub\n", effect);
4738     /* note: According to Jose Roca's GDI+ Docs, this is not implemented
4739      * in Windows's gdiplus */
4740     return NotImplemented;
4741 }
4742
4743 /*****************************************************************************
4744  * GdipSetEffectParameters [GDIPLUS.@]
4745  */
4746 GpStatus WINGDIPAPI GdipSetEffectParameters(CGpEffect *effect,
4747     const VOID *params, const UINT size)
4748 {
4749     static int calls;
4750
4751     TRACE("(%p,%p,%u)\n", effect, params, size);
4752
4753     if(!(calls++))
4754         FIXME("not implemented\n");
4755
4756     return NotImplemented;
4757 }
4758
4759 /*****************************************************************************
4760  * GdipGetImageFlags [GDIPLUS.@]
4761  */
4762 GpStatus WINGDIPAPI GdipGetImageFlags(GpImage *image, UINT *flags)
4763 {
4764     TRACE("%p %p\n", image, flags);
4765
4766     if(!image || !flags)
4767         return InvalidParameter;
4768
4769     *flags = image->flags;
4770
4771     return Ok;
4772 }
4773
4774 GpStatus WINGDIPAPI GdipTestControl(GpTestControlEnum control, void *param)
4775 {
4776     TRACE("(%d, %p)\n", control, param);
4777
4778     switch(control){
4779         case TestControlForceBilinear:
4780             if(param)
4781                 FIXME("TestControlForceBilinear not handled\n");
4782             break;
4783         case TestControlNoICM:
4784             if(param)
4785                 FIXME("TestControlNoICM not handled\n");
4786             break;
4787         case TestControlGetBuildNumber:
4788             *((DWORD*)param) = 3102;
4789             break;
4790     }
4791
4792     return Ok;
4793 }
4794
4795 GpStatus WINGDIPAPI GdipRecordMetafileFileName(GDIPCONST WCHAR* fileName,
4796                             HDC hdc, EmfType type, GDIPCONST GpRectF *pFrameRect,
4797                             MetafileFrameUnit frameUnit, GDIPCONST WCHAR *desc,
4798                             GpMetafile **metafile)
4799 {
4800     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4801                                  frameUnit, debugstr_w(desc), metafile);
4802
4803     return NotImplemented;
4804 }
4805
4806 GpStatus WINGDIPAPI GdipRecordMetafileFileNameI(GDIPCONST WCHAR* fileName, HDC hdc, EmfType type,
4807                             GDIPCONST GpRect *pFrameRect, MetafileFrameUnit frameUnit,
4808                             GDIPCONST WCHAR *desc, GpMetafile **metafile)
4809 {
4810     FIXME("%s %p %d %p %d %s %p stub!\n", debugstr_w(fileName), hdc, type, pFrameRect,
4811                                  frameUnit, debugstr_w(desc), metafile);
4812
4813     return NotImplemented;
4814 }
4815
4816 GpStatus WINGDIPAPI GdipImageForceValidation(GpImage *image)
4817 {
4818     TRACE("%p\n", image);
4819
4820     return Ok;
4821 }
4822
4823 /*****************************************************************************
4824  * GdipGetImageThumbnail [GDIPLUS.@]
4825  */
4826 GpStatus WINGDIPAPI GdipGetImageThumbnail(GpImage *image, UINT width, UINT height,
4827                             GpImage **ret_image, GetThumbnailImageAbort cb,
4828                             VOID * cb_data)
4829 {
4830     GpStatus stat;
4831     GpGraphics *graphics;
4832     UINT srcwidth, srcheight;
4833
4834     TRACE("(%p %u %u %p %p %p)\n",
4835         image, width, height, ret_image, cb, cb_data);
4836
4837     if (!image || !ret_image)
4838         return InvalidParameter;
4839
4840     if (!width) width = 120;
4841     if (!height) height = 120;
4842
4843     GdipGetImageWidth(image, &srcwidth);
4844     GdipGetImageHeight(image, &srcheight);
4845
4846     stat = GdipCreateBitmapFromScan0(width, height, 0, PixelFormat32bppPARGB,
4847         NULL, (GpBitmap**)ret_image);
4848
4849     if (stat == Ok)
4850     {
4851         stat = GdipGetImageGraphicsContext(*ret_image, &graphics);
4852
4853         if (stat == Ok)
4854         {
4855             stat = GdipDrawImageRectRectI(graphics, image,
4856                 0, 0, width, height, 0, 0, srcwidth, srcheight, UnitPixel,
4857                 NULL, NULL, NULL);
4858
4859             GdipDeleteGraphics(graphics);
4860         }
4861
4862         if (stat != Ok)
4863         {
4864             GdipDisposeImage(*ret_image);
4865             *ret_image = NULL;
4866         }
4867     }
4868
4869     return stat;
4870 }
4871
4872 /*****************************************************************************
4873  * GdipImageRotateFlip [GDIPLUS.@]
4874  */
4875 GpStatus WINGDIPAPI GdipImageRotateFlip(GpImage *image, RotateFlipType type)
4876 {
4877     GpBitmap *new_bitmap;
4878     GpBitmap *bitmap;
4879     int bpp, bytesperpixel;
4880     int rotate_90, flip_x, flip_y;
4881     int src_x_offset, src_y_offset;
4882     LPBYTE src_origin;
4883     UINT x, y, width, height;
4884     BitmapData src_lock, dst_lock;
4885     GpStatus stat;
4886
4887     TRACE("(%p, %u)\n", image, type);
4888
4889     if (!image)
4890         return InvalidParameter;
4891
4892     rotate_90 = type&1;
4893     flip_x = (type&6) == 2 || (type&6) == 4;
4894     flip_y = (type&3) == 1 || (type&3) == 2;
4895
4896     if (image->type != ImageTypeBitmap)
4897     {
4898         FIXME("Not implemented for type %i\n", image->type);
4899         return NotImplemented;
4900     }
4901
4902     bitmap = (GpBitmap*)image;
4903     bpp = PIXELFORMATBPP(bitmap->format);
4904
4905     if (bpp < 8)
4906     {
4907         FIXME("Not implemented for %i bit images\n", bpp);
4908         return NotImplemented;
4909     }
4910
4911     if (rotate_90)
4912     {
4913         width = bitmap->height;
4914         height = bitmap->width;
4915     }
4916     else
4917     {
4918         width = bitmap->width;
4919         height = bitmap->height;
4920     }
4921
4922     bytesperpixel = bpp/8;
4923
4924     stat = GdipCreateBitmapFromScan0(width, height, 0, bitmap->format, NULL, &new_bitmap);
4925
4926     if (stat != Ok)
4927         return stat;
4928
4929     stat = GdipBitmapLockBits(bitmap, NULL, ImageLockModeRead, bitmap->format, &src_lock);
4930
4931     if (stat == Ok)
4932     {
4933         stat = GdipBitmapLockBits(new_bitmap, NULL, ImageLockModeWrite, bitmap->format, &dst_lock);
4934
4935         if (stat == Ok)
4936         {
4937             LPBYTE src_row, src_pixel;
4938             LPBYTE dst_row, dst_pixel;
4939
4940             src_origin = src_lock.Scan0;
4941             if (flip_x) src_origin += bytesperpixel * (bitmap->width - 1);
4942             if (flip_y) src_origin += src_lock.Stride * (bitmap->height - 1);
4943
4944             if (rotate_90)
4945             {
4946                 if (flip_y) src_x_offset = -src_lock.Stride;
4947                 else src_x_offset = src_lock.Stride;
4948                 if (flip_x) src_y_offset = -bytesperpixel;
4949                 else src_y_offset = bytesperpixel;
4950             }
4951             else
4952             {
4953                 if (flip_x) src_x_offset = -bytesperpixel;
4954                 else src_x_offset = bytesperpixel;
4955                 if (flip_y) src_y_offset = -src_lock.Stride;
4956                 else src_y_offset = src_lock.Stride;
4957             }
4958
4959             src_row = src_origin;
4960             dst_row = dst_lock.Scan0;
4961             for (y=0; y<height; y++)
4962             {
4963                 src_pixel = src_row;
4964                 dst_pixel = dst_row;
4965                 for (x=0; x<width; x++)
4966                 {
4967                     /* FIXME: This could probably be faster without memcpy. */
4968                     memcpy(dst_pixel, src_pixel, bytesperpixel);
4969                     dst_pixel += bytesperpixel;
4970                     src_pixel += src_x_offset;
4971                 }
4972                 src_row += src_y_offset;
4973                 dst_row += dst_lock.Stride;
4974             }
4975
4976             GdipBitmapUnlockBits(new_bitmap, &dst_lock);
4977         }
4978
4979         GdipBitmapUnlockBits(bitmap, &src_lock);
4980     }
4981
4982     if (stat == Ok)
4983         move_bitmap(bitmap, new_bitmap, FALSE);
4984     else
4985         GdipDisposeImage((GpImage*)new_bitmap);
4986
4987     return stat;
4988 }
4989
4990 /*****************************************************************************
4991  * GdipConvertToEmfPlusToFile [GDIPLUS.@]
4992  */
4993
4994 GpStatus WINGDIPAPI GdipConvertToEmfPlusToFile(const GpGraphics* refGraphics,
4995                                                GpMetafile* metafile, BOOL* conversionSuccess,
4996                                                const WCHAR* filename, EmfType emfType,
4997                                                const WCHAR* description, GpMetafile** out_metafile)
4998 {
4999     FIXME("stub: %p, %p, %p, %p, %u, %p, %p\n", refGraphics, metafile, conversionSuccess, filename, emfType, description, out_metafile);
5000     return NotImplemented;
5001 }