1 // Copyright 2018 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "testing/utils/bitmap_saver.h"
6
7 #include <fstream>
8 #include <vector>
9
10 #include "core/fxcrt/fx_safe_types.h"
11 #include "testing/image_diff/image_diff_png.h"
12 #include "third_party/base/check.h"
13
14 // static
WriteBitmapToPng(FPDF_BITMAP bitmap,const std::string & filename)15 void BitmapSaver::WriteBitmapToPng(FPDF_BITMAP bitmap,
16 const std::string& filename) {
17 const int stride = FPDFBitmap_GetStride(bitmap);
18 const int width = FPDFBitmap_GetWidth(bitmap);
19 const int height = FPDFBitmap_GetHeight(bitmap);
20 CHECK(stride >= 0);
21 CHECK(width >= 0);
22 CHECK(height >= 0);
23 FX_SAFE_FILESIZE size = stride;
24 size *= height;
25 auto input = pdfium::make_span(
26 static_cast<const uint8_t*>(FPDFBitmap_GetBuffer(bitmap)),
27 pdfium::base::ValueOrDieForType<size_t>(size));
28
29 std::vector<uint8_t> png;
30 int format = FPDFBitmap_GetFormat(bitmap);
31 if (format == FPDFBitmap_Gray) {
32 png = image_diff_png::EncodeGrayPNG(input, width, height, stride);
33 } else if (format == FPDFBitmap_BGR) {
34 png = image_diff_png::EncodeBGRPNG(input, width, height, stride);
35 } else {
36 png = image_diff_png::EncodeBGRAPNG(input, width, height, stride,
37 /*discard_transparency=*/false);
38 }
39
40 DCHECK(!png.empty());
41 DCHECK(filename.size() < 256u);
42
43 std::ofstream png_file;
44 png_file.open(filename, std::ios_base::out | std::ios_base::binary);
45 png_file.write(reinterpret_cast<char*>(&png.front()), png.size());
46 DCHECK(png_file.good());
47 png_file.close();
48 }
49
50 // static
WriteBitmapToPng(CFX_DIBitmap * bitmap,const std::string & filename)51 void BitmapSaver::WriteBitmapToPng(CFX_DIBitmap* bitmap,
52 const std::string& filename) {
53 WriteBitmapToPng(reinterpret_cast<FPDF_BITMAP>(bitmap), filename);
54 }
55