mojo: Fix map of booleans for python bindings.
[chromium-blink-merge.git] / ui / gfx / image / image_util.cc
blob89a3f8c03b84f26921fede698c0d198e045c9ac2
1 // Copyright (c) 2012 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 "ui/gfx/image/image_util.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "third_party/skia/include/core/SkBitmap.h"
9 #include "ui/gfx/codec/jpeg_codec.h"
10 #include "ui/gfx/image/image.h"
11 #include "ui/gfx/image/image_skia.h"
13 namespace gfx {
15 const uint32_t kMinimumVisibleOpacity = 12;
17 // The iOS implementations of the JPEG functions are in image_util_ios.mm.
18 #if !defined(OS_IOS)
19 Image ImageFrom1xJPEGEncodedData(const unsigned char* input,
20 size_t input_size) {
21 scoped_ptr<SkBitmap> bitmap(gfx::JPEGCodec::Decode(input, input_size));
22 if (bitmap.get())
23 return Image::CreateFrom1xBitmap(*bitmap);
25 return Image();
28 bool JPEG1xEncodedDataFromImage(const Image& image, int quality,
29 std::vector<unsigned char>* dst) {
30 const gfx::ImageSkiaRep& image_skia_rep =
31 image.AsImageSkia().GetRepresentation(1.0f);
32 if (image_skia_rep.scale() != 1.0f)
33 return false;
35 const SkBitmap& bitmap = image_skia_rep.sk_bitmap();
36 SkAutoLockPixels bitmap_lock(bitmap);
38 if (!bitmap.readyToDraw())
39 return false;
41 return gfx::JPEGCodec::Encode(
42 reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)),
43 gfx::JPEGCodec::FORMAT_SkBitmap, bitmap.width(),
44 bitmap.height(),
45 static_cast<int>(bitmap.rowBytes()), quality,
46 dst);
48 #endif // !defined(OS_IOS)
50 bool VisibleMargins(const ImageSkia& image, int* leading, int* trailing) {
51 *leading = 0;
52 *trailing = std::max(1, image.width()) - 1;
53 if (!image.HasRepresentation(1.0))
54 return false;
56 const ImageSkiaRep& rep = image.GetRepresentation(1.0);
57 if (rep.is_null())
58 return false;
60 const SkBitmap& bitmap = rep.sk_bitmap();
61 if (bitmap.isNull() || bitmap.width() == 0)
62 return false;
64 if (bitmap.isOpaque())
65 return true;
67 SkAutoLockPixels l(bitmap);
68 int inner_min = bitmap.width();
69 for (int x = 0; x < bitmap.width(); ++x) {
70 for (int y = 0; y < bitmap.height(); ++y) {
71 if (SkColorGetA(bitmap.getColor(x, y)) > kMinimumVisibleOpacity) {
72 inner_min = x;
73 break;
76 if (inner_min < bitmap.width())
77 break;
80 int inner_max = -1;
81 for (int x = bitmap.width() - 1; x > inner_min; --x) {
82 for (int y = 0; y < bitmap.height(); ++y) {
83 if (SkColorGetA(bitmap.getColor(x, y)) > kMinimumVisibleOpacity) {
84 inner_max = x;
85 break;
88 if (inner_max > -1)
89 break;
92 if (inner_min == bitmap.width()) {
93 *leading = bitmap.width()/2;
94 *trailing = bitmap.width()/2 + 1;
95 return true;
98 *leading = inner_min;
99 *trailing = inner_max;
100 return true;
103 } // namespace gfx