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_binary, 256, 256, true, 4) {
5 void print_data(const SkData* data, const char* name) {
7 SkDebugf("\nxxd -r -p > %s << EOF", name);
8 size_t s = data->size();
9 const uint8_t* d = data->bytes();
10 for (size_t i = 0; i < s; ++i) {
14 SkDebugf("%02x", d[i]);
16 SkDebugf("\nEOF\n\n");
20 sk_sp<SkData> Encode_PPM_B(const SkPixmap& src) {
21 if (src.width() <= 0 || src.height() <= 0 || !src.addr() ||
22 src.colorType() == kUnknown_SkColorType) {
25 SkString s = SkStringPrintf("P6\n%d %d\n255\n", src.width(), src.height());
26 auto result = SkData::MakeUninitialized(s.size() + 3 * src.width() * src.height());
27 uint8_t* ptr = static_cast<uint8_t*>(result->writable_data());
28 memcpy(ptr, s.c_str(), s.size());
30 for (int y = 0; y < src.height(); ++y) {
31 for (int x = 0; x < src.height(); ++x) {
32 SkColor c = src.getColor(x, y);
33 *ptr++ = SkColorGetR(c);
34 *ptr++ = SkColorGetG(c);
35 *ptr++ = SkColorGetB(c);
41 SkBitmap ToBitmap(SkImage * img) {
43 (void)img->asLegacyBitmap(&bitmap, SkImage::kRO_LegacyBitmapMode);
47 void draw(SkCanvas*) {
48 SkBitmap bitmap = ToBitmap(image.get());
49 sk_sp<SkData> data = Encode_PPM_B(bitmap.pixmap());
50 print_data(data.get(), "foo.ppm");