1

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

这是我到目前为止尝试过的,这是有效的,但是复制的图像文件没有格式化为图像文件,所以我不能使用它。

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

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

4

2 回答 2

2

你可以试试这个

--checking if file exist
function doesFileExist( fname, path )

    local results = false

    local filePath = system.pathForFile( fname, path )

    --filePath will be 'nil' if file doesn't exist and the path is 'system.ResourceDirectory'
    if ( filePath ) then
        filePath = io.open( filePath, "r" )
    end

    if ( filePath ) then
        print( "File found: " .. fname )
        --clean up file handles
        filePath:close()
        results = true
    else
        print( "File does not exist: " .. fname )
    end

    return results
end

--copy file to another path
function copyFile( srcName, srcPath, dstName, dstPath, overwrite )

    local results = false

    local srcPath = doesFileExist( srcName, srcPath )

    if ( srcPath == false ) then
        return nil  -- nil = source file not found
    end

    --check to see if destination file already exists
    if not ( overwrite ) then
        if ( fileLib.doesFileExist( dstName, dstPath ) ) then
            return 1  -- 1 = file already exists (don't overwrite)
        end
    end

    --copy the source file to the destination file
    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 open error!" )
        return false
    else
        --read the file from 'system.ResourceDirectory' and write to the destination directory
        local data = rfh:read( "*a" )
        if not ( data ) then
            print( "read error!" )
            return false
        else
            if not ( wfh:write( data ) ) then
                print( "write error!" )
                return false
            end
        end
    end

    results = 2  -- 2 = file copied successfully!

    --clean up file handles
    rfh:close()
    wfh:close()

    return results
end

--copy 'readme.txt' from the 'system.ResourceDirectory' to '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-05T04:01:18.137 回答
0

您的代码中有错误,下一行local imagedata = file:read("*a")必须local imagedata = cfile:read("*a")相同。

除此之外,代码看起来有效并且应该可以正常工作。

于 2013-08-05T04:01:22.323 回答