ue4 android保存图片到相册
时间: 2023-07-28 13:02:36 浏览: 314
在UE4中保存图片到Android相册,可以使用Java Native Interface(JNI)来实现。下面是具体的步骤:
1. 首先,创建一个Blueprint Function Library。在Blueprint Function Library中创建一个名为"SaveImageToGallery"的静态函数。
2. 打开Visual Studio,并将C++代码添加到BPFunctionLibrary.h和BPFunctionLibrary.cpp文件中。代码如下:
// BPFunctionLibrary.h
#pragma once
#include "Kismet/BlueprintFunctionLibrary.h"
#include "BPFunctionLibrary.generated.h"
UCLASS()
class YOURPROJECT_API UBPFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "MyFunctions")
static bool SaveImageToGallery(FString FilePath);
};
// BPFunctionLibrary.cpp
#include "YourProject.h"
#include "BPFunctionLibrary.h"
#include "Android/AndroidJNI.h"
#include "Android/AndroidApplication.h"
bool UBPFunctionLibrary::SaveImageToGallery(FString FilePath)
{
JNIEnv* Env = FAndroidApplication::GetJavaEnv();
if (Env == nullptr)
{
return false;
}
FString ClassName = FString("com/epicgames/ue4/GameActivity");
jclass ClassID = Env->FindClass(TCHAR_TO_UTF8(*ClassName));
if (ClassID == nullptr)
{
return false;
}
jmethodID MethodID = Env->GetStaticMethodID(ClassID, "SaveImageToGallery", "(Ljava/lang/String;)V");
if (MethodID == nullptr)
{
return false;
}
jstring Filename = Env->NewStringUTF(TCHAR_TO_UTF8(*FilePath));
Env->CallStaticVoidMethod(ClassID, MethodID, Filename);
Env->DeleteLocalRef(Filename);
return true;
}
3. 在Java项目中,创建一个名为"GameActivity"的类,并在该类中添加一个名为"SaveImageToGallery"的静态方法。代码如下:
package com.epicgames.ue4;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
public class GameActivity extends android.app.NativeActivity
{
static void SaveImageToGallery(String FilePath)
{
File ImageFile = new File(FilePath);
Bitmap imageBitmap = BitmapFactory.decodeFile(ImageFile.getAbsolutePath());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.ORIENTATION, 0);
values.put(MediaStore.MediaColumns.DATA, ImageFile.getAbsolutePath());
ContentResolver contentResolver = this.getContentResolver();
Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try
{
FileOutputStream fos = contentResolver.openOutputStream(uri);
if (fos != null)
{
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
4. 现在我们可以在UE4中的蓝图中调用"SaveImageToGallery"函数来保存图片到Android相册了。只需传递要保存的图片文件路径即可。
这样,当我们在UE4中运行该蓝图,并调用"SaveImageToGallery"函数时,图片将被保存到Android的相册中。
阅读全文