Png.h revision 06460ef0d7072114ea3280e1650f77f55e7223f4
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#ifndef AAPT_PNG_H
18#define AAPT_PNG_H
19
20#include <iostream>
21#include <string>
22
23#include "android-base/macros.h"
24
25#include "Diagnostics.h"
26#include "Source.h"
27#include "compile/Image.h"
28#include "io/Io.h"
29#include "process/IResourceTableConsumer.h"
30#include "util/BigBuffer.h"
31
32namespace aapt {
33
34// Size in bytes of the PNG signature.
35constexpr size_t kPngSignatureSize = 8u;
36
37struct PngOptions {
38  int grayscale_tolerance = 0;
39};
40
41/**
42 * Deprecated. Removing once new PNG crunching code is proved to be correct.
43 */
44class Png {
45 public:
46  explicit Png(IDiagnostics* diag) : mDiag(diag) {}
47
48  bool process(const Source& source, std::istream* input, BigBuffer* outBuffer,
49               const PngOptions& options);
50
51 private:
52  DISALLOW_COPY_AND_ASSIGN(Png);
53
54  IDiagnostics* mDiag;
55};
56
57/**
58 * An InputStream that filters out unimportant PNG chunks.
59 */
60class PngChunkFilter : public io::InputStream {
61 public:
62  explicit PngChunkFilter(const android::StringPiece& data);
63  virtual ~PngChunkFilter() = default;
64
65  bool Next(const void** buffer, size_t* len) override;
66  void BackUp(size_t count) override;
67
68  bool CanRewind() const override { return true; }
69  bool Rewind() override;
70  size_t ByteCount() const override { return window_start_; }
71
72  bool HadError() const override { return error_; }
73
74 private:
75  DISALLOW_COPY_AND_ASSIGN(PngChunkFilter);
76
77  bool ConsumeWindow(const void** buffer, size_t* len);
78
79  android::StringPiece data_;
80  size_t window_start_ = 0;
81  size_t window_end_ = 0;
82  bool error_ = false;
83};
84
85/**
86 * Reads a PNG from the InputStream into memory as an RGBA Image.
87 */
88std::unique_ptr<Image> ReadPng(IAaptContext* context, io::InputStream* in);
89
90/**
91 * Writes the RGBA Image, with optional 9-patch meta-data, into the OutputStream
92 * as a PNG.
93 */
94bool WritePng(IAaptContext* context, const Image* image,
95              const NinePatch* nine_patch, io::OutputStream* out,
96              const PngOptions& options);
97
98}  // namespace aapt
99
100#endif  // AAPT_PNG_H
101