decode_and_encode.cc (2157B)
1 // Copyright (c) the JPEG XL Project Authors. All rights reserved. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 #include <stdio.h> 7 8 #include <string> 9 10 #include "lib/extras/codec.h" 11 #include "lib/jxl/base/data_parallel.h" 12 #include "lib/jxl/base/span.h" 13 #include "lib/jxl/base/status.h" 14 #include "tools/file_io.h" 15 #include "tools/thread_pool_internal.h" 16 17 namespace { 18 19 // Reads an input file (typically PNM) with color_space hint and writes to an 20 // output file (typically PNG) which supports all required metadata. 21 int Convert(int argc, char** argv) { 22 if (argc != 4) { 23 fprintf(stderr, "Args: in colorspace_description out\n"); 24 return 1; 25 } 26 const std::string& pathname_in = argv[1]; 27 const std::string& desc = argv[2]; 28 const std::string& pathname_out = argv[3]; 29 30 std::vector<uint8_t> encoded_in; 31 if (!jpegxl::tools::ReadFile(pathname_in, &encoded_in)) { 32 fprintf(stderr, "Failed to read image from %s\n", pathname_in.c_str()); 33 return 1; 34 } 35 jxl::extras::PackedPixelFile ppf; 36 jxl::extras::ColorHints color_hints; 37 jpegxl::tools::ThreadPoolInternal pool(4); 38 color_hints.Add("color_space", desc); 39 if (!jxl::extras::DecodeBytes(jxl::Bytes(encoded_in), color_hints, &ppf)) { 40 fprintf(stderr, "Failed to decode %s\n", pathname_in.c_str()); 41 return 1; 42 } 43 44 jxl::ColorEncoding internal; 45 if (!internal.FromExternal(ppf.color_encoding) || internal.ICC().empty()) { 46 fprintf(stderr, 47 "Failed to generate ICC profile from colorspace description\n"); 48 return 1; 49 } 50 // Roundtrip so that the chromaticities are populated even for enum values. 51 ppf.color_encoding = internal.ToExternal(); 52 ppf.icc = internal.ICC(); 53 54 std::vector<uint8_t> encoded_out; 55 if (!jxl::Encode(ppf, pathname_out, &encoded_out, &pool)) { 56 fprintf(stderr, "Failed to encode %s\n", pathname_out.c_str()); 57 return 1; 58 } 59 if (!jpegxl::tools::WriteFile(pathname_out, encoded_out)) { 60 fprintf(stderr, "Failed to write %s\n", pathname_out.c_str()); 61 return 1; 62 } 63 64 return 0; 65 } 66 67 } // namespace 68 69 int main(int argc, char** argv) { return Convert(argc, argv); }