Unity调用Android保存图片到相册

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/AWNUXCVBN/article/details/50737168
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();

                
                
            }
        });
    }
}

展开阅读全文

没有更多推荐了,返回首页