将图像文件复制到手机存储中。

如何将资源目录中的图像文件复制到文档目录?

这是我至今为止尝试过的,这是有效的,但复制的图像文件不是图像文件格式,所以我无法使用它。

local path = system.pathForFile( "mypicture.png", system.ResourceDirectory )
local cfile = assert(io.open(path, "rb"))

if cfile then
    local imagedata = file:read("*a")
    io.close(file)

    local pathTo = system.pathForFile("mypicture.png", system.DocumentsDirectory)
    local file = io.open( pathTo, "w")

    file:write( imagedata )
    io.close( file )
    file = nil
else
    return nil
end

还有其他方法可以从资源目录复制图像吗?

点赞
用户1682268
用户1682268
<!--检查文件是否存在-->
function doesFileExist( fname, path )

    local results = false

    local filePath = system.pathForFile( fname, path )

    <!--如果文件不存在且路径为“system.ResourceDirectory”,则filePath将为“nil”-->
    if ( filePath ) then
        filePath = io.open( filePath, "r" )
    end

    if ( filePath ) then
        print( "文件找到:" .. fname )
        <!--清理文件句柄-->
        filePath:close()
        results = true
    else
        print( "文件不存在:" .. fname )
    end

    return results
end

<!--将文件复制到另一路径-->
function copyFile( srcName, srcPath, dstName, dstPath, overwrite )

    local results = false

    local srcPath = doesFileExist( srcName, srcPath )

    if ( srcPath == false ) then
        return nil  <!--nil = 源文件不存在-->
    end

    <!--检查目标文件是否已经存在-->
    if not ( overwrite ) then
        if ( fileLib.doesFileExist( dstName, dstPath ) ) then
            return 1  <!--1 = 文件已经存在(不覆盖)-->
        end
    end

    <!--将源文件复制到目标文件-->
    local rfilePath = system.pathForFile( srcName, srcPath )
    local wfilePath = system.pathForFile( dstName, dstPath )

    local rfh = io.open( rfilePath, "rb" )
    local wfh = io.open( wfilePath, "wb" )

    if not ( wfh ) then
        print( "writeFileName 打开错误!" )
        return false
    else
        <!--从'system.ResourceDirectory'读取文件并写入目标目录-->
        local data = rfh:read( "*a" )
        if not ( data ) then
            print( "读取错误!" )
            return false
        else
            if not ( wfh:write( data ) ) then
                print( "写入错误!" )
                return false
            end
        end
    end

    results = 2  <!--2 = 文件复制成功!-->

    <!--清理文件句柄-->
    rfh:close()
    wfh:close()

    return results
end

<!--将“readme.txt”从'system.ResourceDirectory'复制到'system.DocumentsDirectory'-->
copyFile( "readme.txt", nil, "readme.txt", system.DocumentsDirectory, true )

此代码的参考http://docs.coronalabs.com/guide/data/readWriteFiles/index.html#copying-files-to-subfolders

2013-08-05 04:01:18
用户735446
用户735446

你的代码中有错误,local imagedata = file:read("*a") 应该改为 local imagedata = cfile:read("*a"),下一行同理。

除此之外,代码看起来是正确的,应该能够正常工作。

2013-08-05 04:01:22