• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3 #include "tools/fiddle/examples.h"
4 REG_FIDDLE(SkImage_to_PPM_ascii, 256, 256, true, 4) {
dump_txt(const SkData * data,const char * name)5 void dump_txt(const SkData* data, const char* name) {
6     if (data) {
7         SkDebugf("\ncat > %s << EOF\n", name);
8         size_t s = data->size();
9         const char* d = (const char*)data->bytes();
10         while (s > 0) {
11             int l = (int)std::min(s, (size_t)1024);
12             SkDebugf("%.*s", l, d);
13             s -= l;
14             d += l;
15         }
16         SkDebugf("\nEOF\n\n");
17     }
18 }
19 
Encode_PPM_A(const SkPixmap & src)20 sk_sp<SkData> Encode_PPM_A(const SkPixmap& src) {
21     if (src.width() <= 0 || src.height() <= 0 || !src.addr() ||
22         src.colorType() == kUnknown_SkColorType) {
23         return nullptr;
24     }
25     SkDynamicMemoryWStream buf;
26     SkString s = SkStringPrintf("P3\n%d %d\n255\n", src.width(), src.height());
27     buf.write(s.c_str(), s.size());
28     for (int y = 0; y < src.height(); ++y) {
29         for (int x = 0; x < src.height(); ++x) {
30             char buffer[13];
31             SkColor c = src.getColor(x, y);
32             int n = snprintf(buffer, sizeof(buffer), "%d %d %d\n", SkColorGetR(c),
33                              SkColorGetG(c), SkColorGetB(c));
34             if (n < 6 || n + 1 > (int)sizeof(buffer)) {
35                 return nullptr;
36             }
37             buf.write(buffer, n);
38         }
39     }
40     return buf.detachAsData();
41 }
42 
ToBitmap(SkImage * img)43 SkBitmap ToBitmap(SkImage * img) {
44     SkBitmap bitmap;
45     (void)img->asLegacyBitmap(&bitmap, SkImage::kRO_LegacyBitmapMode);
46     return bitmap;
47 }
48 
draw(SkCanvas *)49 void draw(SkCanvas*) {
50     SkBitmap bitmap = ToBitmap(image.get());
51     sk_sp<SkData> data = Encode_PPM_A(bitmap.pixmap());
52     dump_txt(data.get(), "fooa.ppm");
53 }
54 }  // END FIDDLE
55