• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // Save image
11 
12 #include "./image_enc.h"
13 
14 #include <assert.h>
15 #include <string.h>
16 
17 #ifdef WEBP_HAVE_PNG
18 #include <png.h>
19 #include <setjmp.h>   // note: this must be included *after* png.h
20 #endif
21 
22 #ifdef HAVE_WINCODEC_H
23 #ifdef __MINGW32__
24 #define INITGUID  // Without this GUIDs are declared extern and fail to link
25 #endif
26 #define CINTERFACE
27 #define COBJMACROS
28 #define _WIN32_IE 0x500  // Workaround bug in shlwapi.h when compiling C++
29                          // code with COBJMACROS.
30 #include <ole2.h>  // CreateStreamOnHGlobal()
31 #include <shlwapi.h>
32 #include <tchar.h>
33 #include <windows.h>
34 #include <wincodec.h>
35 #endif
36 
37 #include "./imageio_util.h"
38 #include "../examples/unicode.h"
39 
40 //------------------------------------------------------------------------------
41 // PNG
42 
43 #ifdef HAVE_WINCODEC_H
44 
45 #define IFS(fn)                                                     \
46   do {                                                              \
47     if (SUCCEEDED(hr)) {                                            \
48       hr = (fn);                                                    \
49       if (FAILED(hr)) fprintf(stderr, #fn " failed %08lx\n", hr);   \
50     }                                                               \
51   } while (0)
52 
53 #ifdef __cplusplus
54 #define MAKE_REFGUID(x) (x)
55 #else
56 #define MAKE_REFGUID(x) &(x)
57 #endif
58 
CreateOutputStream(const char * out_file_name,int write_to_mem,IStream ** stream)59 static HRESULT CreateOutputStream(const char* out_file_name,
60                                   int write_to_mem, IStream** stream) {
61   HRESULT hr = S_OK;
62   if (write_to_mem) {
63     // Output to a memory buffer. This is freed when 'stream' is released.
64     IFS(CreateStreamOnHGlobal(NULL, TRUE, stream));
65   } else {
66     IFS(SHCreateStreamOnFile((const LPTSTR)out_file_name,
67                              STGM_WRITE | STGM_CREATE, stream));
68   }
69   if (FAILED(hr)) {
70     _ftprintf(stderr, _T("Error opening output file %s (%08lx)\n"),
71               (const LPTSTR)out_file_name, hr);
72   }
73   return hr;
74 }
75 
WriteUsingWIC(const char * out_file_name,int use_stdout,REFGUID container_guid,uint8_t * rgb,int stride,uint32_t width,uint32_t height,int has_alpha)76 static HRESULT WriteUsingWIC(const char* out_file_name, int use_stdout,
77                              REFGUID container_guid,
78                              uint8_t* rgb, int stride,
79                              uint32_t width, uint32_t height, int has_alpha) {
80   HRESULT hr = S_OK;
81   IWICImagingFactory* factory = NULL;
82   IWICBitmapFrameEncode* frame = NULL;
83   IWICBitmapEncoder* encoder = NULL;
84   IStream* stream = NULL;
85   WICPixelFormatGUID pixel_format = has_alpha ? GUID_WICPixelFormat32bppBGRA
86                                               : GUID_WICPixelFormat24bppBGR;
87 
88   if (out_file_name == NULL || rgb == NULL) return E_INVALIDARG;
89 
90   IFS(CoInitialize(NULL));
91   IFS(CoCreateInstance(MAKE_REFGUID(CLSID_WICImagingFactory), NULL,
92                        CLSCTX_INPROC_SERVER,
93                        MAKE_REFGUID(IID_IWICImagingFactory),
94                        (LPVOID*)&factory));
95   if (hr == REGDB_E_CLASSNOTREG) {
96     fprintf(stderr,
97             "Couldn't access Windows Imaging Component (are you running "
98             "Windows XP SP3 or newer?). PNG support not available. "
99             "Use -ppm or -pgm for available PPM and PGM formats.\n");
100   }
101   IFS(CreateOutputStream(out_file_name, use_stdout, &stream));
102   IFS(IWICImagingFactory_CreateEncoder(factory, container_guid, NULL,
103                                        &encoder));
104   IFS(IWICBitmapEncoder_Initialize(encoder, stream,
105                                    WICBitmapEncoderNoCache));
106   IFS(IWICBitmapEncoder_CreateNewFrame(encoder, &frame, NULL));
107   IFS(IWICBitmapFrameEncode_Initialize(frame, NULL));
108   IFS(IWICBitmapFrameEncode_SetSize(frame, width, height));
109   IFS(IWICBitmapFrameEncode_SetPixelFormat(frame, &pixel_format));
110   IFS(IWICBitmapFrameEncode_WritePixels(frame, height, stride,
111                                         height * stride, rgb));
112   IFS(IWICBitmapFrameEncode_Commit(frame));
113   IFS(IWICBitmapEncoder_Commit(encoder));
114 
115   if (SUCCEEDED(hr) && use_stdout) {
116     HGLOBAL image;
117     IFS(GetHGlobalFromStream(stream, &image));
118     if (SUCCEEDED(hr)) {
119       HANDLE std_output = GetStdHandle(STD_OUTPUT_HANDLE);
120       DWORD mode;
121       const BOOL update_mode = GetConsoleMode(std_output, &mode);
122       const void* const image_mem = GlobalLock(image);
123       DWORD bytes_written = 0;
124 
125       // Clear output processing if necessary, then output the image.
126       if (update_mode) SetConsoleMode(std_output, 0);
127       if (!WriteFile(std_output, image_mem, (DWORD)GlobalSize(image),
128                      &bytes_written, NULL) ||
129           bytes_written != GlobalSize(image)) {
130         hr = E_FAIL;
131       }
132       if (update_mode) SetConsoleMode(std_output, mode);
133       GlobalUnlock(image);
134     }
135   }
136 
137   if (frame != NULL) IUnknown_Release(frame);
138   if (encoder != NULL) IUnknown_Release(encoder);
139   if (factory != NULL) IUnknown_Release(factory);
140   if (stream != NULL) IUnknown_Release(stream);
141   return hr;
142 }
143 
WebPWritePNG(const char * out_file_name,int use_stdout,const WebPDecBuffer * const buffer)144 int WebPWritePNG(const char* out_file_name, int use_stdout,
145                  const WebPDecBuffer* const buffer) {
146   const uint32_t width = buffer->width;
147   const uint32_t height = buffer->height;
148   uint8_t* const rgb = buffer->u.RGBA.rgba;
149   const int stride = buffer->u.RGBA.stride;
150   const int has_alpha = WebPIsAlphaMode(buffer->colorspace);
151 
152   return SUCCEEDED(WriteUsingWIC(out_file_name, use_stdout,
153                                  MAKE_REFGUID(GUID_ContainerFormatPng),
154                                  rgb, stride, width, height, has_alpha));
155 }
156 
157 #elif defined(WEBP_HAVE_PNG)    // !HAVE_WINCODEC_H
PNGErrorFunction(png_structp png,png_const_charp unused)158 static void PNGAPI PNGErrorFunction(png_structp png, png_const_charp unused) {
159   (void)unused;  // remove variable-unused warning
160   longjmp(png_jmpbuf(png), 1);
161 }
162 
WebPWritePNG(FILE * out_file,const WebPDecBuffer * const buffer)163 int WebPWritePNG(FILE* out_file, const WebPDecBuffer* const buffer) {
164   volatile png_structp png;
165   volatile png_infop info;
166 
167   if (out_file == NULL || buffer == NULL) return 0;
168 
169   png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
170                                 NULL, PNGErrorFunction, NULL);
171   if (png == NULL) {
172     return 0;
173   }
174   info = png_create_info_struct(png);
175   if (info == NULL) {
176     png_destroy_write_struct((png_structpp)&png, NULL);
177     return 0;
178   }
179   if (setjmp(png_jmpbuf(png))) {
180     png_destroy_write_struct((png_structpp)&png, (png_infopp)&info);
181     return 0;
182   }
183   png_init_io(png, out_file);
184   {
185     const uint32_t width = buffer->width;
186     const uint32_t height = buffer->height;
187     png_bytep row = buffer->u.RGBA.rgba;
188     const int stride = buffer->u.RGBA.stride;
189     const int has_alpha = WebPIsAlphaMode(buffer->colorspace);
190     uint32_t y;
191 
192     png_set_IHDR(png, info, width, height, 8,
193                  has_alpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB,
194                  PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
195                  PNG_FILTER_TYPE_DEFAULT);
196     png_write_info(png, info);
197     for (y = 0; y < height; ++y) {
198       png_write_rows(png, &row, 1);
199       row += stride;
200     }
201   }
202   png_write_end(png, info);
203   png_destroy_write_struct((png_structpp)&png, (png_infopp)&info);
204   return 1;
205 }
206 #else    // !HAVE_WINCODEC_H && !WEBP_HAVE_PNG
WebPWritePNG(FILE * fout,const WebPDecBuffer * const buffer)207 int WebPWritePNG(FILE* fout, const WebPDecBuffer* const buffer) {
208   if (fout == NULL || buffer == NULL) return 0;
209 
210   fprintf(stderr, "PNG support not compiled. Please install the libpng "
211           "development package before building.\n");
212   fprintf(stderr, "You can run with -ppm flag to decode in PPM format.\n");
213   return 0;
214 }
215 #endif
216 
217 //------------------------------------------------------------------------------
218 // PPM / PAM
219 
WritePPMPAM(FILE * fout,const WebPDecBuffer * const buffer,int alpha)220 static int WritePPMPAM(FILE* fout, const WebPDecBuffer* const buffer,
221                        int alpha) {
222   if (fout == NULL || buffer == NULL) {
223     return 0;
224   } else {
225     const uint32_t width = buffer->width;
226     const uint32_t height = buffer->height;
227     const uint8_t* row = buffer->u.RGBA.rgba;
228     const int stride = buffer->u.RGBA.stride;
229     const size_t bytes_per_px = alpha ? 4 : 3;
230     uint32_t y;
231 
232     if (row == NULL) return 0;
233 
234     if (alpha) {
235       fprintf(fout, "P7\nWIDTH %u\nHEIGHT %u\nDEPTH 4\nMAXVAL 255\n"
236                     "TUPLTYPE RGB_ALPHA\nENDHDR\n", width, height);
237     } else {
238       fprintf(fout, "P6\n%u %u\n255\n", width, height);
239     }
240     for (y = 0; y < height; ++y) {
241       if (fwrite(row, width, bytes_per_px, fout) != bytes_per_px) {
242         return 0;
243       }
244       row += stride;
245     }
246   }
247   return 1;
248 }
249 
WebPWritePPM(FILE * fout,const WebPDecBuffer * const buffer)250 int WebPWritePPM(FILE* fout, const WebPDecBuffer* const buffer) {
251   return WritePPMPAM(fout, buffer, 0);
252 }
253 
WebPWritePAM(FILE * fout,const WebPDecBuffer * const buffer)254 int WebPWritePAM(FILE* fout, const WebPDecBuffer* const buffer) {
255   return WritePPMPAM(fout, buffer, 1);
256 }
257 
258 //------------------------------------------------------------------------------
259 // Raw PGM
260 
261 // Save 16b mode (RGBA4444, RGB565, ...) for debugging purpose.
WebPWrite16bAsPGM(FILE * fout,const WebPDecBuffer * const buffer)262 int WebPWrite16bAsPGM(FILE* fout, const WebPDecBuffer* const buffer) {
263   const uint32_t width = buffer->width;
264   const uint32_t height = buffer->height;
265   const uint8_t* rgba = buffer->u.RGBA.rgba;
266   const int stride = buffer->u.RGBA.stride;
267   const uint32_t bytes_per_px = 2;
268   uint32_t y;
269 
270   if (fout == NULL || buffer == NULL || rgba == NULL) return 0;
271 
272   fprintf(fout, "P5\n%u %u\n255\n", width * bytes_per_px, height);
273   for (y = 0; y < height; ++y) {
274     if (fwrite(rgba, width, bytes_per_px, fout) != bytes_per_px) {
275       return 0;
276     }
277     rgba += stride;
278   }
279   return 1;
280 }
281 
282 //------------------------------------------------------------------------------
283 // BMP (see https://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage)
284 
PutLE16(uint8_t * const dst,uint32_t value)285 static void PutLE16(uint8_t* const dst, uint32_t value) {
286   dst[0] = (value >> 0) & 0xff;
287   dst[1] = (value >> 8) & 0xff;
288 }
289 
PutLE32(uint8_t * const dst,uint32_t value)290 static void PutLE32(uint8_t* const dst, uint32_t value) {
291   PutLE16(dst + 0, (value >>  0) & 0xffff);
292   PutLE16(dst + 2, (value >> 16) & 0xffff);
293 }
294 
295 #define BMP_HEADER_SIZE 54
296 #define BMP_HEADER_ALPHA_EXTRA_SIZE 16  // for alpha info
WebPWriteBMP(FILE * fout,const WebPDecBuffer * const buffer)297 int WebPWriteBMP(FILE* fout, const WebPDecBuffer* const buffer) {
298   const int has_alpha = WebPIsAlphaMode(buffer->colorspace);
299   const int header_size =
300       BMP_HEADER_SIZE + (has_alpha ? BMP_HEADER_ALPHA_EXTRA_SIZE : 0);
301   const uint32_t width = buffer->width;
302   const uint32_t height = buffer->height;
303   const uint8_t* rgba = buffer->u.RGBA.rgba;
304   const int stride = buffer->u.RGBA.stride;
305   const uint32_t bytes_per_px = has_alpha ? 4 : 3;
306   uint32_t y;
307   const uint32_t line_size = bytes_per_px * width;
308   const uint32_t bmp_stride = (line_size + 3) & ~3;   // pad to 4
309   const uint32_t image_size = bmp_stride * height;
310   const uint32_t total_size =  image_size + header_size;
311   uint8_t bmp_header[BMP_HEADER_SIZE + BMP_HEADER_ALPHA_EXTRA_SIZE] = { 0 };
312 
313   if (fout == NULL || buffer == NULL || rgba == NULL) return 0;
314 
315   // bitmap file header
316   PutLE16(bmp_header + 0, 0x4d42);                // signature 'BM'
317   PutLE32(bmp_header + 2, total_size);            // size including header
318   PutLE32(bmp_header + 6, 0);                     // reserved
319   PutLE32(bmp_header + 10, header_size);          // offset to pixel array
320   // bitmap info header
321   PutLE32(bmp_header + 14, header_size - 14);     // DIB header size
322   PutLE32(bmp_header + 18, width);                // dimensions
323   PutLE32(bmp_header + 22, height);               // no vertical flip
324   PutLE16(bmp_header + 26, 1);                    // number of planes
325   PutLE16(bmp_header + 28, bytes_per_px * 8);     // bits per pixel
326   PutLE32(bmp_header + 30, has_alpha ? 3 : 0);    // BI_BITFIELDS or BI_RGB
327   PutLE32(bmp_header + 34, image_size);
328   PutLE32(bmp_header + 38, 2400);                 // x pixels/meter
329   PutLE32(bmp_header + 42, 2400);                 // y pixels/meter
330   PutLE32(bmp_header + 46, 0);                    // number of palette colors
331   PutLE32(bmp_header + 50, 0);                    // important color count
332   if (has_alpha) {  // BITMAPV3INFOHEADER complement
333     PutLE32(bmp_header + 54, 0x00ff0000);         // red mask
334     PutLE32(bmp_header + 58, 0x0000ff00);         // green mask
335     PutLE32(bmp_header + 62, 0x000000ff);         // blue mask
336     PutLE32(bmp_header + 66, 0xff000000);         // alpha mask
337   }
338 
339   // TODO(skal): color profile
340 
341   // write header
342   if (fwrite(bmp_header, header_size, 1, fout) != 1) {
343     return 0;
344   }
345 
346   // write pixel array, bottom to top
347   for (y = 0; y < height; ++y) {
348     const uint8_t* const src = &rgba[(uint64_t)(height - 1 - y) * stride];
349     if (fwrite(src, line_size, 1, fout) != 1) {
350       return 0;
351     }
352     // write padding zeroes
353     if (bmp_stride != line_size) {
354       const uint8_t zeroes[3] = { 0 };
355       if (fwrite(zeroes, bmp_stride - line_size, 1, fout) != 1) {
356         return 0;
357       }
358     }
359   }
360   return 1;
361 }
362 #undef BMP_HEADER_SIZE
363 #undef BMP_HEADER_ALPHA_EXTRA_SIZE
364 
365 //------------------------------------------------------------------------------
366 // TIFF
367 
368 #define NUM_IFD_ENTRIES 15
369 #define EXTRA_DATA_SIZE 16
370 // 10b for signature/header + n * 12b entries + 4b for IFD terminator:
371 #define EXTRA_DATA_OFFSET (10 + 12 * NUM_IFD_ENTRIES + 4)
372 #define TIFF_HEADER_SIZE (EXTRA_DATA_OFFSET + EXTRA_DATA_SIZE)
373 
WebPWriteTIFF(FILE * fout,const WebPDecBuffer * const buffer)374 int WebPWriteTIFF(FILE* fout, const WebPDecBuffer* const buffer) {
375   const int has_alpha = WebPIsAlphaMode(buffer->colorspace);
376   const uint32_t width = buffer->width;
377   const uint32_t height = buffer->height;
378   const uint8_t* rgba = buffer->u.RGBA.rgba;
379   const int stride = buffer->u.RGBA.stride;
380   const uint8_t bytes_per_px = has_alpha ? 4 : 3;
381   const uint8_t assoc_alpha =
382       WebPIsPremultipliedMode(buffer->colorspace) ? 1 : 2;
383   // For non-alpha case, we omit tag 0x152 (ExtraSamples).
384   const uint8_t num_ifd_entries = has_alpha ? NUM_IFD_ENTRIES
385                                             : NUM_IFD_ENTRIES - 1;
386   uint8_t tiff_header[TIFF_HEADER_SIZE] = {
387     0x49, 0x49, 0x2a, 0x00,   // little endian signature
388     8, 0, 0, 0,               // offset to the unique IFD that follows
389     // IFD (offset = 8). Entries must be written in increasing tag order.
390     num_ifd_entries, 0,       // Number of entries in the IFD (12 bytes each).
391     0x00, 0x01, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0,    //  10: Width  (TBD)
392     0x01, 0x01, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0,    //  22: Height (TBD)
393     0x02, 0x01, 3, 0, bytes_per_px, 0, 0, 0,     //  34: BitsPerSample: 8888
394         EXTRA_DATA_OFFSET + 0, 0, 0, 0,
395     0x03, 0x01, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0,    //  46: Compression: none
396     0x06, 0x01, 3, 0, 1, 0, 0, 0, 2, 0, 0, 0,    //  58: Photometric: RGB
397     0x11, 0x01, 4, 0, 1, 0, 0, 0,                //  70: Strips offset:
398         TIFF_HEADER_SIZE, 0, 0, 0,               //      data follows header
399     0x12, 0x01, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0,    //  82: Orientation: topleft
400     0x15, 0x01, 3, 0, 1, 0, 0, 0,                //  94: SamplesPerPixels
401         bytes_per_px, 0, 0, 0,
402     0x16, 0x01, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0,    // 106: Rows per strip (TBD)
403     0x17, 0x01, 4, 0, 1, 0, 0, 0, 0, 0, 0, 0,    // 118: StripByteCount (TBD)
404     0x1a, 0x01, 5, 0, 1, 0, 0, 0,                // 130: X-resolution
405         EXTRA_DATA_OFFSET + 8, 0, 0, 0,
406     0x1b, 0x01, 5, 0, 1, 0, 0, 0,                // 142: Y-resolution
407         EXTRA_DATA_OFFSET + 8, 0, 0, 0,
408     0x1c, 0x01, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0,    // 154: PlanarConfiguration
409     0x28, 0x01, 3, 0, 1, 0, 0, 0, 2, 0, 0, 0,    // 166: ResolutionUnit (inch)
410     0x52, 0x01, 3, 0, 1, 0, 0, 0,
411         assoc_alpha, 0, 0, 0,                    // 178: ExtraSamples: rgbA/RGBA
412     0, 0, 0, 0,                                  // 190: IFD terminator
413     // EXTRA_DATA_OFFSET:
414     8, 0, 8, 0, 8, 0, 8, 0,      // BitsPerSample
415     72, 0, 0, 0, 1, 0, 0, 0      // 72 pixels/inch, for X/Y-resolution
416   };
417   uint32_t y;
418 
419   if (fout == NULL || buffer == NULL || rgba == NULL) return 0;
420 
421   // Fill placeholders in IFD:
422   PutLE32(tiff_header + 10 + 8, width);
423   PutLE32(tiff_header + 22 + 8, height);
424   PutLE32(tiff_header + 106 + 8, height);
425   PutLE32(tiff_header + 118 + 8, width * bytes_per_px * height);
426   if (!has_alpha) PutLE32(tiff_header + 178, 0);  // IFD terminator
427 
428   // write header
429   if (fwrite(tiff_header, sizeof(tiff_header), 1, fout) != 1) {
430     return 0;
431   }
432   // write pixel values
433   for (y = 0; y < height; ++y) {
434     if (fwrite(rgba, bytes_per_px, width, fout) != width) {
435       return 0;
436     }
437     rgba += stride;
438   }
439 
440   return 1;
441 }
442 
443 #undef TIFF_HEADER_SIZE
444 #undef EXTRA_DATA_OFFSET
445 #undef EXTRA_DATA_SIZE
446 #undef NUM_IFD_ENTRIES
447 
448 //------------------------------------------------------------------------------
449 // Raw Alpha
450 
WebPWriteAlphaPlane(FILE * fout,const WebPDecBuffer * const buffer)451 int WebPWriteAlphaPlane(FILE* fout, const WebPDecBuffer* const buffer) {
452   if (fout == NULL || buffer == NULL) {
453     return 0;
454   } else {
455     const uint32_t width = buffer->width;
456     const uint32_t height = buffer->height;
457     const uint8_t* a = buffer->u.YUVA.a;
458     const int a_stride = buffer->u.YUVA.a_stride;
459     uint32_t y;
460 
461     if (a == NULL) return 0;
462 
463     fprintf(fout, "P5\n%u %u\n255\n", width, height);
464     for (y = 0; y < height; ++y) {
465       if (fwrite(a, width, 1, fout) != 1) return 0;
466       a += a_stride;
467     }
468     return 1;
469   }
470 }
471 
472 //------------------------------------------------------------------------------
473 // PGM with IMC4 layout
474 
WebPWritePGM(FILE * fout,const WebPDecBuffer * const buffer)475 int WebPWritePGM(FILE* fout, const WebPDecBuffer* const buffer) {
476   if (fout == NULL || buffer == NULL) {
477     return 0;
478   } else {
479     const int width = buffer->width;
480     const int height = buffer->height;
481     const WebPYUVABuffer* const yuv = &buffer->u.YUVA;
482     const uint8_t* src_y = yuv->y;
483     const uint8_t* src_u = yuv->u;
484     const uint8_t* src_v = yuv->v;
485     const uint8_t* src_a = yuv->a;
486     const int uv_width = (width + 1) / 2;
487     const int uv_height = (height + 1) / 2;
488     const int a_height = (src_a != NULL) ? height : 0;
489     int ok = 1;
490     int y;
491 
492     if (src_y == NULL || src_u == NULL || src_v == NULL) return 0;
493 
494     fprintf(fout, "P5\n%d %d\n255\n",
495             (width + 1) & ~1, height + uv_height + a_height);
496     for (y = 0; ok && y < height; ++y) {
497       ok &= (fwrite(src_y, width, 1, fout) == 1);
498       if (width & 1) fputc(0, fout);    // padding byte
499       src_y += yuv->y_stride;
500     }
501     for (y = 0; ok && y < uv_height; ++y) {
502       ok &= (fwrite(src_u, uv_width, 1, fout) == 1);
503       ok &= (fwrite(src_v, uv_width, 1, fout) == 1);
504       src_u += yuv->u_stride;
505       src_v += yuv->v_stride;
506     }
507     for (y = 0; ok && y < a_height; ++y) {
508       ok &= (fwrite(src_a, width, 1, fout) == 1);
509       if (width & 1) fputc(0, fout);    // padding byte
510       src_a += yuv->a_stride;
511     }
512     return ok;
513   }
514 }
515 
516 //------------------------------------------------------------------------------
517 // Raw YUV(A) planes
518 
WebPWriteYUV(FILE * fout,const WebPDecBuffer * const buffer)519 int WebPWriteYUV(FILE* fout, const WebPDecBuffer* const buffer) {
520   if (fout == NULL || buffer == NULL) {
521     return 0;
522   } else {
523     const int width = buffer->width;
524     const int height = buffer->height;
525     const WebPYUVABuffer* const yuv = &buffer->u.YUVA;
526     const uint8_t* src_y = yuv->y;
527     const uint8_t* src_u = yuv->u;
528     const uint8_t* src_v = yuv->v;
529     const uint8_t* src_a = yuv->a;
530     const int uv_width = (width + 1) / 2;
531     const int uv_height = (height + 1) / 2;
532     const int a_height = (src_a != NULL) ? height : 0;
533     int ok = 1;
534     int y;
535 
536     if (src_y == NULL || src_u == NULL || src_v == NULL) return 0;
537 
538     for (y = 0; ok && y < height; ++y) {
539       ok &= (fwrite(src_y, width, 1, fout) == 1);
540       src_y += yuv->y_stride;
541     }
542     for (y = 0; ok && y < uv_height; ++y) {
543       ok &= (fwrite(src_u, uv_width, 1, fout) == 1);
544       src_u += yuv->u_stride;
545     }
546     for (y = 0; ok && y < uv_height; ++y) {
547       ok &= (fwrite(src_v, uv_width, 1, fout) == 1);
548       src_v += yuv->v_stride;
549     }
550     for (y = 0; ok && y < a_height; ++y) {
551       ok &= (fwrite(src_a, width, 1, fout) == 1);
552       src_a += yuv->a_stride;
553     }
554     return ok;
555   }
556 }
557 
558 //------------------------------------------------------------------------------
559 // Generic top-level call
560 
WebPSaveImage(const WebPDecBuffer * const buffer,WebPOutputFileFormat format,const char * const out_file_name)561 int WebPSaveImage(const WebPDecBuffer* const buffer,
562                   WebPOutputFileFormat format,
563                   const char* const out_file_name) {
564   FILE* fout = NULL;
565   int needs_open_file = 1;
566   const int use_stdout =
567       (out_file_name != NULL) && !WSTRCMP(out_file_name, "-");
568   int ok = 1;
569 
570   if (buffer == NULL || out_file_name == NULL) return 0;
571 
572 #ifdef HAVE_WINCODEC_H
573   needs_open_file = (format != PNG);
574 #endif
575 
576   if (needs_open_file) {
577     fout = use_stdout ? ImgIoUtilSetBinaryMode(stdout)
578                       : WFOPEN(out_file_name, "wb");
579     if (fout == NULL) {
580       WFPRINTF(stderr, "Error opening output file %s\n",
581                (const W_CHAR*)out_file_name);
582       return 0;
583     }
584   }
585 
586   if (format == PNG ||
587       format == RGBA || format == BGRA || format == ARGB ||
588       format == rgbA || format == bgrA || format == Argb) {
589 #ifdef HAVE_WINCODEC_H
590     ok &= WebPWritePNG(out_file_name, use_stdout, buffer);
591 #else
592     ok &= WebPWritePNG(fout, buffer);
593 #endif
594   } else if (format == PAM) {
595     ok &= WebPWritePAM(fout, buffer);
596   } else if (format == PPM || format == RGB || format == BGR) {
597     ok &= WebPWritePPM(fout, buffer);
598   } else if (format == RGBA_4444 || format == RGB_565 || format == rgbA_4444) {
599     ok &= WebPWrite16bAsPGM(fout, buffer);
600   } else if (format == BMP) {
601     ok &= WebPWriteBMP(fout, buffer);
602   } else if (format == TIFF) {
603     ok &= WebPWriteTIFF(fout, buffer);
604   } else if (format == RAW_YUV) {
605     ok &= WebPWriteYUV(fout, buffer);
606   } else if (format == PGM || format == YUV || format == YUVA) {
607     ok &= WebPWritePGM(fout, buffer);
608   } else if (format == ALPHA_PLANE_ONLY) {
609     ok &= WebPWriteAlphaPlane(fout, buffer);
610   }
611   if (fout != NULL && fout != stdout) {
612     fclose(fout);
613   }
614   return ok;
615 }
616