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