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
;
18 JavaBitmap::JavaBitmap(jobject bitmap
)
21 int err
= AndroidBitmap_lockPixels(AttachCurrentThread(), bitmap_
, &pixels_
);
25 AndroidBitmapInfo info
;
26 err
= AndroidBitmap_getInfo(AttachCurrentThread(), bitmap_
, &info
);
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_
);
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
) {
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());
63 static ScopedJavaLocalRef
<jobject
> CreateJavaBitmapFromResource(
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();
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());
90 SkBitmap
CreateSkBitmapFromResource(const char* name
) {
91 return ConvertToSkBitmap(CreateJavaBitmapFromResource(name
));