1 /* save_jpeg.c - save JPEG image
3 * Raster graphics library
5 * Copyright (c) 2023 Window Maker Team
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
33 #include "imgformat.h"
37 * Save RImage to JPEG image
40 Bool
RSaveJPEG(RImage
*img
, const char *filename
, char *title
)
46 struct jpeg_compress_struct cinfo
;
47 struct jpeg_error_mgr jerr
;
50 file
= fopen(filename
, "wb");
52 RErrorCode
= RERR_OPEN
;
56 if (img
->format
== RRGBAFormat
)
61 /* collect separate RGB values to a buffer */
62 buffer
= malloc(sizeof(char) * 3 * img
->width
* img
->height
);
63 for (y
= 0; y
< img
->height
; y
++) {
64 for (x
= 0; x
< img
->width
; x
++) {
65 RGetPixel(img
, x
, y
, &pixel
);
66 buffer
[y
*img
->width
*3+x
*3+0] = (char)(pixel
.red
);
67 buffer
[y
*img
->width
*3+x
*3+1] = (char)(pixel
.green
);
68 buffer
[y
*img
->width
*3+x
*3+2] = (char)(pixel
.blue
);
72 /* Setup Exception handling */
73 cinfo
.err
= jpeg_std_error(&jerr
);
75 /* Initialize cinfo structure */
76 jpeg_create_compress(&cinfo
);
77 jpeg_stdio_dest(&cinfo
, file
);
79 cinfo
.image_width
= img
->width
;
80 cinfo
.image_height
= img
->height
;
81 cinfo
.input_components
= 3;
82 cinfo
.in_color_space
= JCS_RGB
;
84 jpeg_set_defaults(&cinfo
);
85 jpeg_set_quality(&cinfo
, 85, TRUE
);
86 jpeg_start_compress(&cinfo
, TRUE
);
88 /* Set title if any */
90 jpeg_write_marker(&cinfo
, JPEG_COM
, (const JOCTET
*)title
, strlen(title
));
92 while (cinfo
.next_scanline
< cinfo
.image_height
) {
93 row_pointer
= (JSAMPROW
) &buffer
[cinfo
.next_scanline
* img_depth
* img
->width
];
94 jpeg_write_scanlines(&cinfo
, &row_pointer
, 1);
97 jpeg_finish_compress(&cinfo
);