Caching images from url to txt file

Hey, i tried to cache url img to txt file and i didn’t succeed, what’s wrong?



MAT = {}
MAT.Loaded = {}

function MAT:Init()
	local mainDir = file.Exists( "imgcache", "DATA" )
	if not mainDir then file.CreateDir( "imgcache" ) end
end

function MAT:CacheToFile( id, url )
	http.Fetch( url, function( body, len, headers, code ) 
		file.Write( "imgcache/" .. id .. ".txt", util.Base64Encode( body ) )
		MAT.Loaded[id] = Material( "../data/imgcache/" .. id .. ".txt", "smooth" )
	end,
	function( err )
		print(err)
	end )
end

function MAT:GetMatFromFile( id )
	return MAT.Loaded[id]
end

MAT:Init()
MAT:CacheToFile( "hl3logo", "http://futuretechs.eu/hl3.png" )


And to load:



hook.Add( "HUDPaint", "Hl3 test", function()
	surface.SetDrawColor( Color( 255, 255, 255 ) )
	surface.SetMaterial( MAT:GetMatFromFile( "hl3logo" ) )
	surface.DrawTexturedRect( 10, 10, 512, 512 )
end )


Thanks!

you cant access anything outside which you “cache” in http.fetch.

A little side note, make sure you only create the material once, as creating one every frame will be very resource expensive.

Material() doesn’t load txt files. Use the newline trick (.txt
.png).