1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 #pragma once 18 19 #include <string> 20 21 #include "BigBuffer.h" 22 #include "IDiagnostics.h" 23 #include "Image.h" 24 #include "Source.h" 25 #include "Streams.h" 26 #include "android-base/macros.h" 27 28 namespace android { 29 // Size in bytes of the PNG signature. 30 constexpr size_t kPngSignatureSize = 8u; 31 32 struct PngOptions { 33 int grayscale_tolerance = 0; 34 // By default we want small files and can take the performance hit to achieve this goal. 35 int compression_level = 9; 36 }; 37 38 /** 39 * Deprecated. Removing once new PNG crunching code is proved to be correct. 40 */ 41 class Png { 42 public: Png(IDiagnostics * diag)43 explicit Png(IDiagnostics* diag) : mDiag(diag) { 44 } 45 46 bool process(const Source& source, std::istream* input, BigBuffer* outBuffer, 47 const PngOptions& options); 48 49 private: 50 DISALLOW_COPY_AND_ASSIGN(Png); 51 52 IDiagnostics* mDiag; 53 }; 54 55 /** 56 * An InputStream that filters out unimportant PNG chunks. 57 */ 58 class PngChunkFilter : public InputStream { 59 public: 60 explicit PngChunkFilter(StringPiece data); 61 virtual ~PngChunkFilter() = default; 62 63 bool Next(const void** buffer, size_t* len) override; 64 void BackUp(size_t count) override; 65 CanRewind()66 bool CanRewind() const override { 67 return true; 68 } 69 bool Rewind() override; ByteCount()70 size_t ByteCount() const override { 71 return window_start_; 72 } 73 HadError()74 bool HadError() const override { 75 return !error_msg_.empty(); 76 } GetError()77 std::string GetError() const override { 78 return error_msg_; 79 } 80 81 private: 82 DISALLOW_COPY_AND_ASSIGN(PngChunkFilter); 83 84 bool ConsumeWindow(const void** buffer, size_t* len); 85 86 StringPiece data_; 87 size_t window_start_ = 0; 88 size_t window_end_ = 0; 89 std::string error_msg_; 90 }; 91 /** 92 * Reads a PNG from the InputStream into memory as an RGBA Image. 93 */ 94 std::unique_ptr<Image> ReadPng(InputStream* in, IDiagnostics* diag); 95 96 /** 97 * Writes the RGBA Image, with optional 9-patch meta-data, into the OutputStream 98 * as a PNG. 99 */ 100 bool WritePng(const Image* image, const NinePatch* nine_patch, OutputStream* out, 101 const PngOptions& options, IDiagnostics* diag, bool verbose); 102 } // namespace android