1 // Copyright 2018 PDFium Authors. All rights reserved.
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/logging.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 if (FPDFBitmap_GetFormat(bitmap) == FPDFBitmap_Gray) {
31 png = image_diff_png::EncodeGrayPNG(input, width, height, stride);
32 } else {
33 png = image_diff_png::EncodeBGRAPNG(input, width, height, stride,
34 /*discard_transparency=*/false);
35 }
36
37 DCHECK(!png.empty());
38 DCHECK(filename.size() < 256u);
39
40 std::ofstream png_file;
41 png_file.open(filename, std::ios_base::out | std::ios_base::binary);
42 png_file.write(reinterpret_cast<char*>(&png.front()), png.size());
43 DCHECK(png_file.good());
44 png_file.close();
45 }
46
47 // static
WriteBitmapToPng(CFX_DIBitmap * bitmap,const std::string & filename)48 void BitmapSaver::WriteBitmapToPng(CFX_DIBitmap* bitmap,
49 const std::string& filename) {
50 WriteBitmapToPng(reinterpret_cast<FPDF_BITMAP>(bitmap), filename);
51 }
52