Support toDataURL without 1x representation
authorKevin Sawicki <kevinsawicki@gmail.com>
Mon, 6 Mar 2017 21:24:50 +0000 (13:24 -0800)
committerKevin Sawicki <kevinsawicki@gmail.com>
Tue, 7 Mar 2017 20:27:55 +0000 (12:27 -0800)
atom/common/api/atom_api_native_image.cc
atom/common/api/atom_api_native_image.h
spec/api-native-image-spec.js

index 0c17494..95531b1 100644 (file)
@@ -21,6 +21,7 @@
 #include "net/base/data_url.h"
 #include "third_party/skia/include/core/SkPixelRef.h"
 #include "ui/base/layout.h"
+#include "ui/base/webui/web_ui_util.h"
 #include "ui/gfx/codec/jpeg_codec.h"
 #include "ui/gfx/codec/png_codec.h"
 #include "ui/gfx/geometry/size.h"
@@ -257,12 +258,12 @@ v8::Local<v8::Value> NativeImage::ToJPEG(v8::Isolate* isolate, int quality) {
 }
 
 std::string NativeImage::ToDataURL() {
-  scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
-  std::string data_url;
-  data_url.insert(data_url.end(), png->front(), png->front() + png->size());
-  base::Base64Encode(data_url, &data_url);
-  data_url.insert(0, "data:image/png;base64,");
-  return data_url;
+  if (HasRepresentation(1.0)) {
+    scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
+    return webui::GetPngDataUrl(png->front(), png->size());
+  } else {
+    return webui::GetBitmapDataUrl(image_.AsBitmap());
+  }
 }
 
 v8::Local<v8::Value> NativeImage::GetBitmap(v8::Isolate* isolate) {
@@ -297,6 +298,10 @@ bool NativeImage::IsEmpty() {
   return image_.IsEmpty();
 }
 
+bool NativeImage::HasRepresentation(float scale_factor) {
+  return image_.AsImageSkia().HasRepresentation(scale_factor);
+}
+
 gfx::Size NativeImage::GetSize() {
   return image_.Size();
 }
@@ -468,6 +473,7 @@ void NativeImage::BuildPrototype(
       .SetMethod("resize", &NativeImage::Resize)
       .SetMethod("crop", &NativeImage::Crop)
       .SetMethod("getAspectRatio", &NativeImage::GetAspectRatio)
+      .SetMethod("hasRepresentation", &NativeImage::HasRepresentation)
       // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
       .SetMethod("toPng", &NativeImage::ToPNG)
       .SetMethod("toJpeg", &NativeImage::ToJPEG);
index ee1b5f5..a653f15 100644 (file)
@@ -83,6 +83,7 @@ class NativeImage : public mate::Wrappable<NativeImage> {
                                  const gfx::Rect& rect);
   std::string ToDataURL();
   bool IsEmpty();
+  bool HasRepresentation(float scale_factor);
   gfx::Size GetSize();
   float GetAspectRatio();
 
index 94492ca..9aa0ced 100644 (file)
@@ -9,6 +9,7 @@ describe('nativeImage module', () => {
     it('returns an empty image', () => {
       const empty = nativeImage.createEmpty()
       assert.equal(empty.isEmpty(), true)
+      assert.equal(empty.hasRepresentation(1.0), false)
       assert.equal(empty.getAspectRatio(), 1)
       assert.equal(empty.toDataURL(), 'data:image/png;base64,')
       assert.deepEqual(empty.getSize(), {width: 0, height: 0})