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