Unity调用Android相册以及裁剪功能上传头像
- Android部分
调用相册以及裁剪选中的图片:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends UnityPlayerActivity {
private static final int PHOTO_REQUEST_CODE = 1;// 相册
public static final int PHOTORESOULT = 3;// 结果
private Uri cropImageUri;
private String gameObjectName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void OpenPhoto(String name) {
gameObjectName = name;
Intent intent = new Intent(Intent.ACTION_PICK, null);
// Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
// intent.setType("image/*");
// intent.putExtra("crop", "true");
// intent.putExtra("aspectX", 1);
// intent.putExtra("aspectY", 1);
// intent.putExtra("outputX", 100);
// intent.putExtra("outputY", 100);
// intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTO_REQUEST_CODE);
}
// 读取相册缩放图片
public void startPhotoZoom(Uri uri) {
if (null == uri) {
Log.i("Unity", "读取相册缩放图片 ==>> uri为Null");
}
File CropPhoto = new File(getExternalCacheDir(), "crop_image.jpg");
try {
if (CropPhoto.exists()) {
CropPhoto.delete();
}
CropPhoto.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
cropImageUri = Uri.fromFile(CropPhoto);
// cropImageUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath()
// + "/Android/data/com.YouthGamer.WenZhou/cache/" + "crop_image.jpg");
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 添加这一句表示对目标应用临时授权该Uri所代表的文件
}
// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
// intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true); // no face detection
Log.i("Unity", "开始缩放");
try {
startActivityForResult(intent, PHOTORESOULT);
} catch (Exception e) {
// 解决截取后部分机型秒退
Log.i("Unity", e.getMessage());
e.printStackTrace();
UnityPlayer.UnitySendMessage(gameObjectName, "onImagePath", "Fail");
}
}
public void SaveBitmap(Bitmap bitmap) throws IOException {
if(null == bitmap) {
Log.i("Unity", "SaveBitmap=>bitmap为Null");
}
FileOutputStream fOut = null;
// 注解1
String path = "/mnt/sdcard/Android/data/com.YouthGamer.WenZhou/files";
// String path = "file://" + "/" + Environment.getExternalStorageDirectory().toString()
// + "/Android/data/com.YouthGamer.WenZhou/files";
try {
// 查看这个路径是否存在,
// 如果并没有这个路径,
// 创建这个路径
File destDir = new File(path);
if (!destDir.exists()) {
destDir.mkdirs();
}
fOut = new FileOutputStream(path + "/image.jpg");
} catch (FileNotFoundException e) {
Log.i("Unity", e.getMessage());
e.printStackTrace();
}
// 将Bitmap对象写入本地路径中,Unity在去相同的路径来读取这个文件
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
Log.i("Unity", e.getMessage());
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
Log.i("Unity", e.getMessage());
e.printStackTrace();
}
Log.i("Unity", gameObjectName);
UnityPlayer.UnitySendMessage(gameObjectName, "onImagePath", "image.jpg");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
if (requestCode == PHOTO_REQUEST_CODE) {
Log.i("Unity", "选取相册图片完毕");
startPhotoZoom(data.getData());
} else if (requestCode == PHOTORESOULT) {
try {
Log.i("Unity", "缩放图片完毕,准备保存Bitmap");
Bitmap headShot = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropImageUri));
SaveBitmap(headShot);
} catch (IOException e) {
Log.i("Unity", e.getMessage());
e.printStackTrace();
}
}
}
}
- Unity部分
调用部分
//调用Android的入口方法OpenPhoto
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("OpenPhoto", gameObject.name);
接受部分
/// <summary>
/// android裁剪完图片进行回调
/// </summary>
/// <param name="imageName"></param>
public void onImagePath(string imageName)
{
if (imageName.Contains("Fail"))
{
//失败
}
else
{
Debug.Log("更新图片-3");
StartCoroutine(LoadImage());
}
}
private IEnumerator LoadImage()
{
WWW www = new WWW("file://" + Application.persistentDataPath + "/image.jpg");
yield return www;
if (www.error == null)
{
//开始上传头像--此处根据服务器定的协议进行上传
StartCoroutine(setRoleImage(www.texture));
}
else
{
Debug.LogError("LoadImage>>>www.error:" + www.error);
}
}
别忘了配置AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.YouthGamer.WenZhou"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="23" />
<application
android:allowBackup="true"
android:theme="@android:style/Theme.NoTitleBar"
android:label="@string/app_name"
android:icon="@drawable/app_icon" >
>
<activity
android:name="com.YouthGamer.WenZhou.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 连接互联网的权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
</manifest>
结果: