android-ndk-r21d 调用 FreeImage 实现图片格式转换
之前用opencv转换,感觉就是高射炮打蚊子,还只支持5种图像格式,连gif都不支持。使用FreeImage,它几乎支持所有的图片格式
ImageUtility.cpp
#include <jni.h> #include <iostream> using namespace std; #include "freeimage.h" extern "C" { unsigned char* ImageConvert(unsigned char* imageData, int imageDataSize, const char* format, int* returnSize) { FreeImage_Initialise(); //read bytes to image object FIMEMORY * memory = FreeImage_OpenMemory(imageData, imageDataSize); FREE_IMAGE_FORMAT srcformat = FreeImage_GetFileTypeFromMemory(memory, 0); FIBITMAP *bitmap = FreeImage_LoadFromMemory(srcformat, memory, 0); FreeImage_CloseMemory(memory); //convert image object type FIMEMORY* hmem = FreeImage_OpenMemory(); FreeImage_SaveToMemory(FreeImage_GetFIFFromFilename(format), bitmap, hmem, 0); //save image object type to bytes FreeImage_SeekMemory(hmem, 0, SEEK_END); long bufferSize = FreeImage_TellMemory(hmem); unsigned char* buffer = new unsigned char[bufferSize]; unsigned int actualReadCount = bufferSize; FreeImage_SeekMemory(hmem, 0, SEEK_SET); FreeImage_ReadMemory(buffer, bufferSize, actualReadCount, hmem); FreeImage_CloseMemory(hmem); FreeImage_DeInitialise(); *returnSize = bufferSize; return buffer; } }
Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := FreeImage LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libFreeImage.a include $(PREBUILT_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := ImageUtility LOCAL_SRC_FILES := ImageUtility.cpp LOCAL_STATIC_LIBRARIES := libFreeImage LOCAL_SHORT_COMMANDS := true include $(BUILD_SHARED_LIBRARY)
Application.mk
ADDITIONAL_FLAGS := -O3 -fopenmp -DANDROID -Wno-c++11-narrowing APP_CFLAGS += $(ADDITIONAL_FLAGS) APP_CONLYFLAGS += -std=c11 APP_CPPFLAGS += $(ADDITIONAL_FLAGS) -std=c++11 -fexceptions -frtti APP_PLATFORM := android-21 APP_STL := c++_static APP_ABI := all APP_OPTIM := release APP_SHORT_COMMANDS := true
调用命令 ndk-build 生成 .so
Android java 调用核心代码:
public interface ImageUtility extends Library { public Pointer ImageConvert(Pointer data, int dataSize, String format , Pointer resultSize); } ... //get image bytes async from internet byte[] data = (byte[]) result; ImageUtility imageUtility = (ImageUtility) Native.loadLibrary("ImageUtility", ImageUtility.class); Pointer ptr = new Memory(data.length); ptr.write(0, data, 0, data.length); Pointer returnSize = new Memory(4); Pointer imagePointer = imageUtility.ImageConvert(ptr, data.length, ".gif" , returnSize); byte[] imageBytes = imagePointer.getByteArray(0, returnSize.getInt(0)); Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes,0, imageBytes.length, new BitmapFactory.Options()); ...
其中用到了jna调用so动态链接库
桂棹兮兰桨,击空明兮溯流光。