Unity调用Android保存图片到相册

package com.greengame.pva;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.unity3d.player.UnityPlayerNativeActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends UnityPlayerNativeActivity {
    public static Context context;
    public static MainActivity mainActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mainActivity = this;
    }

    // 保存到相册
    public static void savePng(final String fileName) {

        context = mainActivity.getApplicationContext();

        mainActivity.runOnUiThread(new Runnable() {
            public void run() {

                Bitmap bitmap = BitmapFactory.decodeFile(Environment
                        .getExternalStorageDirectory()
                        + "/Android/data/com.greengame.pva/files/"
                        + fileName
                        + ".png");

                File file = new File(Environment.getExternalStorageDirectory()
                        + "/DCIM/Camera", fileName + ".jpg");

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                bitmap.compress(CompressFormat.JPEG, 100, fos);

                try {
                    fos.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.w("cat", e.toString());
                }
                bitmap.recycle();
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" +Environment.getExternalStorageDirectory()
                        + "/DCIM/Camera/"+fileName + ".jpg")));
                
                Toast.makeText(context, "照片已保存到相册", Toast.LENGTH_SHORT).show();

                
                
            }
        });
    }
}

你可能感兴趣的:(Unity调用Android保存图片到相册)