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