Separate Simple Backend creation from initialization.
[chromium-blink-merge.git] / ui / gfx / android / java_bitmap.cc
bloba19a000fb71844cc259dcd33e5557d3b2303e59a
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/android/java_bitmap.h"
7 #include <android/bitmap.h>
9 #include "base/logging.h"
10 #include "jni/BitmapHelper_jni.h"
11 #include "third_party/skia/include/core/SkBitmap.h"
12 #include "ui/gfx/size.h"
14 using base::android::AttachCurrentThread;
16 namespace gfx {
18 JavaBitmap::JavaBitmap(jobject bitmap)
19 : bitmap_(bitmap),
20 pixels_(NULL) {
21 int err = AndroidBitmap_lockPixels(AttachCurrentThread(), bitmap_, &pixels_);
22 DCHECK(!err);
23 DCHECK(pixels_);
25 AndroidBitmapInfo info;
26 err = AndroidBitmap_getInfo(AttachCurrentThread(), bitmap_, &info);
27 DCHECK(!err);
28 size_ = gfx::Size(info.width, info.height);
29 format_ = info.format;
30 stride_ = info.stride;
33 JavaBitmap::~JavaBitmap() {
34 int err = AndroidBitmap_unlockPixels(AttachCurrentThread(), bitmap_);
35 DCHECK(!err);
38 // static
39 bool JavaBitmap::RegisterJavaBitmap(JNIEnv* env) {
40 return ui::RegisterNativesImpl(env);
43 ScopedJavaLocalRef<jobject> CreateJavaBitmap(const gfx::Size& size) {
44 return ui::Java_BitmapHelper_createBitmap(AttachCurrentThread(),
45 size.width(), size.height());
48 ScopedJavaLocalRef<jobject> ConvertToJavaBitmap(const SkBitmap* skbitmap) {
49 DCHECK(skbitmap);
50 DCHECK_EQ(skbitmap->bytesPerPixel(), 4);
52 ScopedJavaLocalRef<jobject> jbitmap =
53 CreateJavaBitmap(gfx::Size(skbitmap->width(), skbitmap->height()));
54 SkAutoLockPixels src_lock(*skbitmap);
55 JavaBitmap dst_lock(jbitmap.obj());
56 void* src_pixels = skbitmap->getPixels();
57 void* dst_pixels = dst_lock.pixels();
58 memcpy(dst_pixels, src_pixels, skbitmap->getSize());
60 return jbitmap;
63 static ScopedJavaLocalRef<jobject> CreateJavaBitmapFromResource(
64 const char* name) {
65 JNIEnv* env = AttachCurrentThread();
66 ScopedJavaLocalRef<jstring> jname(env, env->NewStringUTF(name));
67 return ui::Java_BitmapHelper_decodeDrawableResource(env, jname.obj());
70 static SkBitmap ConvertToSkBitmap(ScopedJavaLocalRef<jobject> jbitmap) {
71 JavaBitmap src_lock(jbitmap.obj());
72 DCHECK_EQ(src_lock.format(), ANDROID_BITMAP_FORMAT_RGBA_8888);
74 gfx::Size src_size = src_lock.size();
76 SkBitmap skbitmap;
77 skbitmap.setConfig(SkBitmap::kARGB_8888_Config,
78 src_size.width(), src_size.height(), src_lock.stride());
79 skbitmap.allocPixels();
80 SkAutoLockPixels dst_lock(skbitmap);
82 void* src_pixels = src_lock.pixels();
83 void* dst_pixels = skbitmap.getPixels();
85 memcpy(dst_pixels, src_pixels, skbitmap.getSize());
87 return skbitmap;
90 SkBitmap CreateSkBitmapFromResource(const char* name) {
91 return ConvertToSkBitmap(CreateJavaBitmapFromResource(name));
94 } // namespace gfx