2 * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "jpeg_helper.h"
25 namespace StyleTransferApp
28 JpegHelper::JpegHelper(int bytes_per_pixel, J_COLOR_SPACE color_space)
29 : _bytes_per_pixel(bytes_per_pixel), _color_space(color_space)
34 int JpegHelper::readJpeg(const std::string filename, std::vector<float> &raw_image, int width,
37 struct jpeg_decompress_struct cinfo;
38 struct jpeg_error_mgr jerr;
40 FILE *infile = fopen(filename.c_str(), "rb");
41 unsigned long location = 0;
46 printf("Error opening jpeg file %s\n!", filename);
50 cinfo.err = jpeg_std_error(&jerr);
52 jpeg_create_decompress(&cinfo);
54 jpeg_stdio_src(&cinfo, infile);
56 jpeg_read_header(&cinfo, TRUE);
58 jpeg_start_decompress(&cinfo);
60 // TODO: Implement resize function
61 assert(cinfo.output_width == width);
62 assert(cinfo.output_height == height);
64 raw_image.resize(cinfo.output_width * cinfo.output_height * cinfo.num_components);
66 unsigned char *ptr = new unsigned char[cinfo.output_width * cinfo.num_components];
68 while (cinfo.output_scanline < cinfo.image_height)
70 jpeg_read_scanlines(&cinfo, &ptr, 1);
71 for (i = 0; i < cinfo.image_width * cinfo.num_components; i++)
73 raw_image[location++] = static_cast<float>(ptr[i]);
77 jpeg_finish_decompress(&cinfo);
78 jpeg_destroy_decompress(&cinfo);
85 int JpegHelper::writeJpeg(const std::string filename, std::vector<float> &raw_image, int width,
88 struct jpeg_compress_struct cinfo;
89 struct jpeg_error_mgr jerr;
90 unsigned long location = 0;
92 FILE *outfile = fopen(filename.c_str(), "wb");
96 printf("Error opening output jpeg file %s\n!", filename);
99 cinfo.err = jpeg_std_error(&jerr);
100 jpeg_create_compress(&cinfo);
101 jpeg_stdio_dest(&cinfo, outfile);
103 cinfo.image_width = width;
104 cinfo.image_height = height;
105 cinfo.input_components = _bytes_per_pixel;
106 cinfo.in_color_space = _color_space;
108 jpeg_set_defaults(&cinfo);
110 jpeg_start_compress(&cinfo, TRUE);
112 unsigned char *ptr = new unsigned char[cinfo.image_width * cinfo.input_components];
114 while (cinfo.next_scanline < cinfo.image_height)
116 for (int i = 0; i < cinfo.image_width * cinfo.input_components; i++)
118 ptr[i] = static_cast<unsigned char>(raw_image[location++]);
120 jpeg_write_scanlines(&cinfo, &ptr, 1);
123 jpeg_finish_compress(&cinfo);
127 jpeg_destroy_compress(&cinfo);
132 } // namespace StyleTransferApp