Home | History | Annotate | Download | only in tools
      1 /*
      2  * Copyright 2014 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #include "Resources.h"
      9 #include "SkBitmap.h"
     10 #include "SkCommandLineFlags.h"
     11 #include "SkData.h"
     12 #include "SkImage.h"
     13 #include "SkImageGenerator.h"
     14 #include "SkOSFile.h"
     15 #include "SkOSPath.h"
     16 #include "SkStream.h"
     17 #include "SkTypeface.h"
     18 
     19 DEFINE_string2(resourcePath, i, "resources", "Directory with test resources: images, fonts, etc.");
     20 
     21 SkString GetResourcePath(const char* resource) {
     22     return SkOSPath::Join(FLAGS_resourcePath[0], resource);
     23 }
     24 
     25 void SetResourcePath(const char* resource) {
     26     FLAGS_resourcePath.set(0, resource);
     27 }
     28 
     29 bool GetResourceAsBitmap(const char* resource, SkBitmap* dst) {
     30     SkString resourcePath = GetResourcePath(resource);
     31     sk_sp<SkData> resourceData(SkData::MakeFromFileName(resourcePath.c_str()));
     32     std::unique_ptr<SkImageGenerator> gen(SkImageGenerator::MakeFromEncoded(resourceData));
     33     if (!gen) {
     34         return false;
     35     }
     36     return dst->tryAllocPixels(gen->getInfo()) &&
     37         gen->getPixels(gen->getInfo().makeColorSpace(nullptr), dst->getPixels(), dst->rowBytes(),
     38                        nullptr);
     39 }
     40 
     41 sk_sp<SkImage> GetResourceAsImage(const char* resource) {
     42     SkString path = GetResourcePath(resource);
     43     sk_sp<SkData> resourceData(SkData::MakeFromFileName(path.c_str()));
     44     return SkImage::MakeFromEncoded(resourceData);
     45 }
     46 
     47 SkStreamAsset* GetResourceAsStream(const char* resource) {
     48     SkString resourcePath = GetResourcePath(resource);
     49     std::unique_ptr<SkFILEStream> stream(new SkFILEStream(resourcePath.c_str()));
     50     if (!stream->isValid()) {
     51         SkDebugf("Resource %s not found.\n", resource);
     52         return nullptr;
     53     }
     54     return stream.release();
     55 }
     56 
     57 sk_sp<SkData> GetResourceAsData(const char* resource) {
     58     SkString resourcePath = GetResourcePath(resource);
     59     return SkData::MakeFromFileName(resourcePath.c_str());
     60 }
     61 
     62 sk_sp<SkTypeface> MakeResourceAsTypeface(const char* resource) {
     63     std::unique_ptr<SkStreamAsset> stream(GetResourceAsStream(resource));
     64     if (!stream) {
     65         return nullptr;
     66     }
     67     return SkTypeface::MakeFromStream(stream.release());
     68 }
     69