使用 JNI 和 NDK 旋转位图

问题描述 投票:0回答:2

背景:

我决定,由于位图占用大量内存,很容易导致内存不足错误,因此我将把艰苦的、消耗内存的工作放在 C/C++ 代码上。

我用于旋转位图的步骤是:

  1. 读取位图信息(宽度,高度)
  2. 将位图像素存储到数组中。
  3. 回收位图。
  4. 创建一个相反大小的新位图。
  5. 将像素放入新的位图中。
  6. 释放像素并返回位图。

问题:

尽管一切似乎都运行没有任何错误,但输出图像并不是原始图像的旋转。事实上,它完全毁了它。

旋转应该是逆时针,90度。

我得到的示例(屏幕截图已放大):

enter image description here

正如你所看到的,不仅颜色变得更奇怪,而且尺寸也与我设置的不匹配。这里确实有些奇怪。

也许我没有正确读取/输入数据?

当然这只是一个例子。只要设备有足够的内存来容纳该代码,该代码就可以在任何位图上正常工作。另外,除了旋转位图之外,我可能还想对位图执行其他操作。

我创建的代码:

Android.mk 文件:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := JniTest
LOCAL_SRC_FILES := JniTest.cpp
LOCAL_LDLIBS := -llog
LOCAL_LDFLAGS += -ljnigraphics
include $(BUILD_SHARED_LIBRARY)
APP_OPTIM := debug
LOCAL_CFLAGS := -g

.cpp 文件:

#include <jni.h>
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <android/bitmap.h>
#include <cstring>
#include <unistd.h>

#define  LOG_TAG    "DEBUG"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)

extern "C"
  {
  JNIEXPORT jobject JNICALL Java_com_example_jnitest_MainActivity_rotateBitmapCcw90(JNIEnv * env, jobject obj, jobject bitmap);
  }

JNIEXPORT jobject JNICALL Java_com_example_jnitest_MainActivity_rotateBitmapCcw90(JNIEnv * env, jobject obj, jobject bitmap)
  {
  //
  //getting bitmap info:
  //
  LOGD("reading bitmap info...");
  AndroidBitmapInfo info;
  int ret;
  if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0)
    {
    LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
    return NULL;
    }
  LOGD("width:%d height:%d stride:%d", info.width, info.height, info.stride);
  if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888)
    {
    LOGE("Bitmap format is not RGBA_8888!");
    return NULL;
    }
  //
  //read pixels of bitmap into native memory :
  //
  LOGD("reading bitmap pixels...");
  void* bitmapPixels;
  if ((ret = AndroidBitmap_lockPixels(env, bitmap, &bitmapPixels)) < 0)
    {
    LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
    return NULL;
    }
  uint32_t* src = (uint32_t*) bitmapPixels;
  uint32_t* tempPixels = new uint32_t[info.height * info.width];
  int stride = info.stride;
  int pixelsCount = info.height * info.width;
  memcpy(tempPixels, src, sizeof(uint32_t) * pixelsCount);
  AndroidBitmap_unlockPixels(env, bitmap);
  //
  //recycle bitmap - using bitmap.recycle()
  //
  LOGD("recycling bitmap...");
  jclass bitmapCls = env->GetObjectClass(bitmap);
  jmethodID recycleFunction = env->GetMethodID(bitmapCls, "recycle", "()V");
  if (recycleFunction == 0)
    {
    LOGE("error recycling!");
    return NULL;
    }
  env->CallVoidMethod(bitmap, recycleFunction);
  //
  //creating a new bitmap to put the pixels into it - using Bitmap Bitmap.createBitmap (int width, int height, Bitmap.Config config) :
  //
  LOGD("creating new bitmap...");
  jmethodID createBitmapFunction = env->GetStaticMethodID(bitmapCls, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
  jstring configName = env->NewStringUTF("ARGB_8888");
  jclass bitmapConfigClass = env->FindClass("android/graphics/Bitmap$Config");
  jmethodID valueOfBitmapConfigFunction = env->GetStaticMethodID(bitmapConfigClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
  jobject bitmapConfig = env->CallStaticObjectMethod(bitmapConfigClass, valueOfBitmapConfigFunction, configName);
  jobject newBitmap = env->CallStaticObjectMethod(bitmapCls, createBitmapFunction, info.height, info.width, bitmapConfig);
  //
  // putting the pixels into the new bitmap:
  //
  if ((ret = AndroidBitmap_lockPixels(env, newBitmap, &bitmapPixels)) < 0)
    {
    LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
    return NULL;
    }
  uint32_t* newBitmapPixels = (uint32_t*) bitmapPixels;
  int whereToPut = 0;    
  for (int x = info.width - 1; x >= 0; --x)
    for (int y = 0; y < info.height; ++y)
      {
      uint32_t pixel = tempPixels[info.width * y + x];
      newBitmapPixels[whereToPut++] = pixel;
      }
  AndroidBitmap_unlockPixels(env, newBitmap);
  //
  // freeing the native memory used to store the pixels
  //
  delete[] tempPixels;
  return newBitmap;
  }

java文件:

  static
    {
    System.loadLibrary("JniTest");
    }

  /**
   * rotates a bitmap by 90 degrees counter-clockwise . <br/>
   * notes:<br/>
   * -the input bitmap will be recycled and shouldn't be used anymore <br/>
   * -returns the rotated bitmap . <br/>
   * -could take some time , so do the operation in a new thread
   */
  public native Bitmap rotateBitmapCcw90(Bitmap bitmap);

...
  Bitmap rotatedImage=rotateBitmapCcw90(bitmapToRotate);

编辑:在我得到答案后,我希望与大家分享这段代码和注释:

  • 为了使其正常工作,我在代码中将“uint16_t”的每个实例替换为“uint32_t”(这是我询问过的代码中的错误)。

  • 输入和输出位图必须使用8888配置(即ARGB)

  • 输入位图在此过程中将被回收。

  • 代码将图像逆时针旋转 90 度。当然你可以根据自己的需要更改。


更好的解决方案

我已经发表了一篇很好的文章,其中包含此功能和其他功能,这里.

android bitmap android-ndk java-native-interface image-rotation
2个回答
6
投票

由于您使用的是

ARGB_8888
格式,因此每个像素都是
uint32_t
而不是
uint16_t
。尝试更改旋转位图创建以将
uint32_t
用于源数组和目标数组,它应该可以更好地工作。


0
投票

我尝试了三星 S5(Android 6,API 21),但没有看到使用 JNI 代码和

Bitmap.createBitmap()
:

之间的区别
val bitmapHolder = JniBitmapHolder()
bitmapHolder.storeBitmap(bitmap)
bitmapHolder.rotateBitmapCw90()
bitmapHolder.bitmapAndFree

抛出 OutOfMemoryError“无法分配 63489036 字节 分配 16776704 个可用字节和 39MB,直到 OOM” AndroidBitmap_lockPixels() 失败!错误=-1 java.lang.OutOfMemoryError:无法分配 63489036 字节 分配 16776704 个可用字节和 39MB,直到 OOM dalvik.system.VMRuntime.newNonMovableArray(本机方法)位于 android.graphics.Bitmap.nativeCreate(本机方法)位于 android.graphics.Bitmap.createBitmap(Bitmap.java:975) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:946) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:913) 在 com.jni.bitmap_operations.JniBitmapHolder.jniGetBitmapFromStoredBitmapData(本机 方法)在 com.jni.bitmap_operations.JniBitmapHolder.getBitmap(JniBitmapHolder.java:88) 在 com.jni.bitmap_operations.JniBitmapHolder.getBitmapAndFree(JniBitmapHolder.java:93)

vs

Bitmap.createBitmap(
   bitmap,
    0,
    0,
     bitmap.width,
     bitmap.height,
     matrix,
   true
)

抛出 OutOfMemoryError“无法分配 63489036 字节 分配 16765968 可用字节和 39MB,直到 OOM” java.lang.OutOfMemoryError:无法分配 63489036 字节 分配 16765968 可用字节和 39MB,直到 OOM dalvik.system.VMRuntime.newNonMovableArray(本机方法)位于 android.graphics.Bitmap.nativeCreate(本机方法)位于 android.graphics.Bitmap.createBitmap(Bitmap.java:975) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:946) 在 android.graphics.Bitmap.createBitmap(Bitmap.java:877)

因此,仅添加

largeHeap
会有帮助,否则根本无法在此类设备上工作

附注我试图旋转从相机获得的

2988x5312
(16兆像素相机)的位图(以最高可用分辨率捕获照片)

已更新

bitmap.recycle()
之后添加
bitmapHolder.storeBitmap(bitmap)
以使其正常工作!

val bitmapHolder = JniBitmapHolder()
bitmapHolder.storeBitmap(bitmap)
bitmap.recycle()
bitmapHolder.rotateBitmapCw90()
bitmapHolder.bitmapAndFree
© www.soinside.com 2019 - 2024. All rights reserved.