1 // Copyright 2014 The Chromium 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.
5 #include "components/enhanced_bookmarks/image_store_util.h"
7 #import <UIKit/UIKit.h>
9 #include "base/mac/scoped_cftyperef.h"
10 #include "base/mac/scoped_nsobject.h"
11 #include "third_party/skia/include/core/SkBitmap.h"
12 #include "ui/gfx/color_analysis.h"
15 // An implementation of RefCountedMemory, where the bytes are stored in a
16 // NSData. This class assumes the NSData is non mutable to avoid a copy.
17 class RefCountedNSDataMemory : public base::RefCountedMemory {
19 explicit RefCountedNSDataMemory(NSData* memory) : data_([memory retain]) {}
21 const unsigned char* front() const override {
22 return reinterpret_cast<const unsigned char*>([data_ bytes]);
25 size_t size() const override { return [data_ length]; }
28 ~RefCountedNSDataMemory() override {}
30 base::scoped_nsobject<NSData> data_;
31 DISALLOW_COPY_AND_ASSIGN(RefCountedNSDataMemory);
35 namespace enhanced_bookmarks {
37 // Encodes the UIImage representation of a gfx::Image.
38 scoped_refptr<base::RefCountedMemory> BytesForImage(const gfx::Image& image) {
39 DCHECK(image.HasRepresentation(gfx::Image::kImageRepCocoaTouch));
40 return scoped_refptr<RefCountedNSDataMemory>(new RefCountedNSDataMemory(
41 [NSKeyedArchiver archivedDataWithRootObject:image.ToUIImage()]));
44 // Decodes the UIImage in the bytes and returns a gfx::Image.
45 gfx::Image ImageForBytes(const scoped_refptr<base::RefCountedMemory>& data) {
46 return gfx::Image([[NSKeyedUnarchiver unarchiveObjectWithData:
47 [NSData dataWithBytes:data->front() length:data->size()]] retain]);
50 SkColor DominantColorForImage(const gfx::Image& image) {
51 return color_utils::CalculateKMeanColorOfBitmap(*image.ToSkBitmap());
54 } // namespace enhanced_bookmarks