Android保存图片到系统相册

先说一下思路,我是这样做的,先保存一张图片到可写路径下,用cocos2d的节点截屏功能,保存之后就可以 保存Bitmap到本地指定路径下 ,然后通过广播,通知系统相册图库刷新数据。

先说如何节点截屏:

--节点截屏
function captureNodeScreen(tag)
    
    local fileName = tag..".jpg"
    local targetPath = cc.FileUtils:getInstance():getWritablePath()..fileName

    -- if not cc.FileUtils:getInstance():isFileExist(targetPath) then
        local winSize = cc.Director:getInstance():getWinSize()
        local sprite = cc.Sprite:create("1.png")
        sprite:setPosition(0,0)
        sprite:setAnchorPoint(0,0)

        -- local qrpath = cc.FileUtils:getInstance():getWritablePath()..PlatformLogic.loginResult.dwUserID..".png"
        -- local qr = ccui.ImageView:create(qrpath)
        -- qr:setPosition(sprite:getContentSize().width/2,qr:getContentSize().width/2+80)
        -- sprite:addChild(qr)
        local target  = cc.RenderTexture:create(sprite:getContentSize().width*sprite:getScale(), sprite:getContentSize().height*sprite:getScale(), cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888, 0x88F0);

        target:begin()

        sprite:visit()

        target:endToLua()

        target:saveToFile(fileName, cc.IMAGE_FORMAT_PNG, false)
    -- end
end

这样呢,我们就可以访问到我们需要保存的图片了,这个时候就可以进行第二步了。

先把lua代码贴出来:

--保存图片到系统相册
function saveSystemPhoto(tag)
    local fileName = tag..".jpg"
    local targetPath = cc.FileUtils:getInstance():getWritablePath()..fileName
    print("targetPath",targetPath);
    if not cc.FileUtils:getInstance():isFileExist(targetPath) then
        return
    end
    if device.platform == "ios" then
    elseif device.platform == "android" then
        local javaClassName = "org.cocos2dx.lua.AppActivity"
        local javaMethodName = "saveImage"
        local javaParams = {targetPath}
        local javaMethodSig = "(Ljava/lang/String;)V"
        local ok,ret  = require("cocos.cocos2d.luaj").callStaticMethod(javaClassName, javaMethodName, javaParams, javaMethodSig)
        if ok == false then
            print("luaoc调用出错 saveSystemPhoto")
        else
            print("保存成功,请到相册中查看")
            return true
        end
    elseif device.platform == "windows" then
        print("保存成功 windows 路径"..targetPath)
        return true
    end

end

再去看看java代码,首先添加权限:



<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

public static AppActivity instance = null;//类静态实例,为了方便后面静态函数的调用
	public static String imagePath = "";
//返回实例
    public static AppActivity getInstance() {
        Log.v("AppActivity","getInstance");
    	return instance;
    }
protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
instance = this;
    }
public static void saveImage(final String path){
    	imagePath = path;
//    	if (realPathFromUri != ""){
    		saveImageFile(imagePath);
//    	}
//    	else{
//    		ActivityCompat.requestPermissions(instance, mPermissionList, 100);    		
//    	}
    }
public static void saveImageFile(final String path)
	{
    	Runnable runnable = new Runnable() {
    	    @SuppressWarnings("deprecation")
    		public void run() {
		    	    	try {
		    				String fileName = null;
		    				//系统相册目录
		    				String galleryPath = Environment.getExternalStorageDirectory()
		    				        + File.separator + Environment.DIRECTORY_DCIM
		    				        +File.separator+"Camera"+File.separator;
		    				
//		    				 if(!Build.BRAND.toLowerCase().equals("meitu") && Build.BRAND.toLowerCase().indexOf("mei") != -1 ){ // 小米手机 
//		    					 galleryPath= Environment.getExternalStorageDirectory()
//				    				        + File.separator + Environment.DIRECTORY_DCIM
//				    				        +File.separator;
//		    			        }
		    				
		    				if(!isExist(galleryPath)){
		    					galleryPath= Environment.getExternalStorageDirectory()
			    				        + File.separator + Environment.DIRECTORY_DCIM
			    				        +File.separator;
		    				}
		    				 
//		    				 galleryPath = realPathFromUri;
		    				 System.out.println(Build.BRAND + "图片保存成功后删除APP里面的暂存图片" + galleryPath);
		                                // 原始文件
                                    File sourceFile = null;
		    			    // 插入到图库的文件
		    				File Imagefile = null;
		    			    FileOutputStream outputStream = null;
		    			    Imagefile = new File(path);
		    			    sourceFile = Imagefile;
		    			    String pngName = Imagefile.getName();
		    			    Bitmap bitmap = BitmapFactory.decodeFile(path);
		    			    Imagefile = new File(galleryPath, pngName);
		    			    fileName = Imagefile.toString();
		    			    outputStream = new FileOutputStream(fileName);
		    			    if (null != outputStream) {
		    			    	bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
		    			    	outputStream.close();
		    			    }
                                    
               MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
		    			           bitmap, fileName, null);
		    			   Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		    			   Uri uri = Uri.fromFile(Imagefile);
		    			   intent.setData(uri);
		    			   getContext().sendBroadcast(intent);  
		    			   System.out.println("图片保存成功后删除APP里面的暂存图片");
		//    			   sourceFile.delete();
		    		}catch(Exception e)
		    		{
		    			System.out.println("输出到图库失败" +  e);
		    		}
    		    }
    	    };
    	instance.runOnUiThread(runnable);
		
}

public static boolean isExist(String path) {
    	File file = new File(path);
    	//判断文件夹是否存在,如果不存在则创建文件夹
    	if (!file.exists()) {
    		return false;
    	}
    	
    	return true;
 }

我想保存的图片是在我本地(1.png),这里可能大家都不一样的,到时候lua传参的时候要注意:

现在我就要保存这张图片,然后把这张图片出现自手机的相册中。调用我们的lua代码:

打包运行一下,我这边运行的结果是:

我们再去看一下手机相册:

成功了,我在手机和模拟器各自试了一下,都是没有问题的。

不过需要注意的是,如果程序刚运行,就直接去保存图片到相册可能会失败,一般稍微延迟一点时间就没有问题了。

Guess you like

Origin blog.csdn.net/pyf_914406232/article/details/96967358