Подгрузка картинки через ссылку

boy next door

Участник
Автор темы
257
23
Версия MoonLoader
.026-beta
всем привет. как сделать подгрузку картинки с ссылки, а не с директории игры?
ибо у меня не всегда срабатывает загрузка фотографии через авто-обнову, та и не хочу в свой скрипт её кидать.
Важно: не называйте подгружаемую картинку logo.png, почему-то с таким названием работать не хочет.
Lua:
local imgui = require 'mimgui'
local WinState = imgui.new.bool()

function main()
sampRegisterChatCommand('cmd', function() WinState[0] = not WinState[0] end)
wait(-1)
end

imgui.OnFrame(function() return WinState[0] and not isPauseMenuActive() end, function(player)
imgui.SetNextWindowPos(imgui.ImVec2(500,500), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(300, 300), imgui.Cond.Always)
imgui.Begin('##Window', WinState,imgui.WindowFlags.NoResize)
imgui.Image(imhandle, imgui.ImVec2(200, 200)) -- эта функция рендерит саму картинку
imgui.End()
end)

imgui.OnInitialize(function()
if doesFileExist(getWorkingDirectory()..'\\resource\\example.png') then -- находим необходимую картинку с названием example.png в папке moonloader/resource/
imhandle = imgui.CreateTextureFromFile(getWorkingDirectory() .. '\\resource\\example.png') -- если найдена, то записываем в переменную хендл картинки
end
end)
1692370682723.png
 

chapo

tg/inst: @moujeek
Модератор
9,064
12,020
 
  • Нравится
Реакции: whyega52

boy next door

Участник
Автор темы
257
23
использовал этот код
Lua:
[18:39:22.697700] (error)   urltest.lua: ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:123: attempt to call global 'asyncHttpRequest' (a nil value)
stack traceback:
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:123: in function 'download'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:158: in function 'ImageURL'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:22: in function '_draw'
    ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:107: in function <...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:91>
[18:39:22.701700] (error)   urltest.lua: Script died due to an error. (20A233E4)

код что я сделал по фасту
Lua:
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local new = imgui.new
local renderWindow = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow)
        imgui.ImageURL("https://items.shinoa.tech/images/model/2296.png", imgui.ImVec2(256, 256), true)
        imgui.End()
    end
)
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('urlt', function()
        renderWindow[0] = not renderWindow[0]
    end)
    while true do
        wait(0)
      
    end
end

local md5 = require "md5"
imgui.ImageURL = {
    cache_dir = getWorkingDirectory() .. "/resource/cache",
    download_statuses = {
        INIT = 0,
        DOWNLOADING = 1,
        ERROR = 2,
        SAVED = 3,
        NOT_MODIFIED = 4,
        CACHE_ONLY = 5
    },
    pool = {}
}
function imgui.ImageURL:set_cache(url, image_data, headers)
    if not doesDirectoryExist(self.cache_dir) then
        createDirectory(self.cache_dir)
    end
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    local file, err = io.open(path, "wb")
    if not file then
        return nil
    end
    local data = { Data = tostring(image_data) }
    if headers["etag"] then
        data["Etag"] = headers["etag"]
    end
    if headers["last-modified"] then
        data["Last-Modified"] = headers["last-modified"]
    end
    file:write(encodeJson(data))
    file:close()
    return path
end
function imgui.ImageURL:get_cache(url)
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    if not doesFileExist(path) then
        return nil, nil
    end
    local image_data = nil
    local cached_headers = {}
    local file, err = io.open(path, "rb")
    if file then
        local cache = decodeJson(file:read("*a"))
        if type(cache) ~= "table" then
            return nil, nil
        end
        if cache["Data"] ~= nil then
               image_data = cache["Data"]
           end
           if cache["Last-Modified"] ~= nil then
               cached_headers["If-Modified-Since"] = cache["Last-Modified"]
           end
           if cache["Etag"] ~= nil then
               cached_headers["If-None-Match"] = cache["Etag"]
           end
        file:close()
    end
    return image_data, cached_headers
end
function imgui.ImageURL:download(url, preload_cache)
    local st = self.download_statuses
    self.pool[url] = {
        status = st.DOWNLOADING,
        image = nil,
        error = nil
    }
    local cached_image, cached_headers = imgui.ImageURL:get_cache(url)
    local img = self.pool[url]
    if preload_cache and cached_image ~= nil then
        img.image = imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
    end
    asyncHttpRequest("GET", url, { headers = cached_headers },
        function(result)
            if result.status_code == 200 then
                img.image = imgui.CreateTextureFromMemory(memory.strptr(result.text), #result.text)
                img.status = st.SAVED
                imgui.ImageURL:set_cache(url, result.text, result.headers)
            elseif result.status_code == 304 then
                img.image = img.image or imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
                img.status = st.NOT_MODIFIED
            else
                img.status = img.image and st.CACHE_ONLY or st.ERROR
                img.error = ("Error #%s"):format(result.status_code)
            end
        end,
        function(error)
            img.status = img.image and st.CACHE_ONLY or st.ERROR
            img.error = error
        end
    )
end
function imgui.ImageURL:render(url, size, preload, ...)
    local st = self.download_statuses
    local img = self.pool[url]
    if img == nil then
        self.pool[url] = {
            status = st.INIT,
            error = nil,
            image = nil
        }
        img = self.pool[url]
    end
    if img.status == st.INIT then
        imgui.ImageURL:download(url, preload)
    end
      
    if img.image ~= nil then
        imgui.Image(img.image, size, ...)
    else
        imgui.Dummy(size)
    end
    return img.status, img.error
end
setmetatable(imgui.ImageURL, {
    __call = imgui.ImageURL.render
})

оно?
Lua:
[18:52:05.463200] (error)   urltest.lua: ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:306: attempt to index upvalue 'renderer' (a nil value)
stack traceback:
    ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:306: in function 'CreateTextureFromFile'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:44: in main chunk
[18:52:05.463200] (error)   urltest.lua: Script died due to an error. (20A23D14)

Lua:
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local new = imgui.new
local renderWindow = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 700, 500
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow)
        imgui.Image(img, imgui.ImVec2(464, 464)--[[размер]])
        imgui.End()
    end
)
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('urlt', function()
        renderWindow[0] = not renderWindow[0]
    end)
    while true do
        wait(0)
        if not doesFileExist("moonloader/resource/image/exampe.jpg") then
            sampAddChatMessage('[{501c5f}MyRecords{FFFFFF}]: Фото не было найдено, началось автоматическое скачивание, не закрывайте игру!', -1)
            download_id = downloadUrlToFile('https://i.imgur.com/kpopR9i.jpeg', 'moonloader/resource/image/exampe.jpeg', function(id, status, p1, p2)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('[{501c5f}MyRecords{FFFFFF}]: Скачивание успешно завершено', -1) end
            end)
        end
    end
end
local img = imgui.CreateTextureFromFile(getWorkingDirectory()..'/resource/image/exampe.jpeg')
 
Последнее редактирование:

MLycoris

На вид оружие массового семяизвержения
Проверенный
1,982
2,186
  • Нравится
Реакции: VanoKLR

MLycoris

На вид оружие массового семяизвержения
Проверенный
1,982
2,186
ну а так хули коды с тем нерабочие?
тебе кинули 2 рабочих примера, а ты через жопу их вставил и совсем не хочешь разбираться, как в остальных своих темах, начни головой думать или бросай луа
 
  • Нравится
Реакции: chapo

OSPx

Участник
41
26
использовал этот код
Lua:
[18:39:22.697700] (error)   urltest.lua: ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:123: attempt to call global 'asyncHttpRequest' (a nil value)
stack traceback:
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:123: in function 'download'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:158: in function 'ImageURL'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:22: in function '_draw'
    ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:107: in function <...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:91>
[18:39:22.701700] (error)   urltest.lua: Script died due to an error. (20A233E4)

код что я сделал по фасту
Lua:
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local new = imgui.new
local renderWindow = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow)
        imgui.ImageURL("https://items.shinoa.tech/images/model/2296.png", imgui.ImVec2(256, 256), true)
        imgui.End()
    end
)
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('urlt', function()
        renderWindow[0] = not renderWindow[0]
    end)
    while true do
        wait(0)
     
    end
end

local md5 = require "md5"
imgui.ImageURL = {
    cache_dir = getWorkingDirectory() .. "/resource/cache",
    download_statuses = {
        INIT = 0,
        DOWNLOADING = 1,
        ERROR = 2,
        SAVED = 3,
        NOT_MODIFIED = 4,
        CACHE_ONLY = 5
    },
    pool = {}
}
function imgui.ImageURL:set_cache(url, image_data, headers)
    if not doesDirectoryExist(self.cache_dir) then
        createDirectory(self.cache_dir)
    end
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    local file, err = io.open(path, "wb")
    if not file then
        return nil
    end
    local data = { Data = tostring(image_data) }
    if headers["etag"] then
        data["Etag"] = headers["etag"]
    end
    if headers["last-modified"] then
        data["Last-Modified"] = headers["last-modified"]
    end
    file:write(encodeJson(data))
    file:close()
    return path
end
function imgui.ImageURL:get_cache(url)
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    if not doesFileExist(path) then
        return nil, nil
    end
    local image_data = nil
    local cached_headers = {}
    local file, err = io.open(path, "rb")
    if file then
        local cache = decodeJson(file:read("*a"))
        if type(cache) ~= "table" then
            return nil, nil
        end
        if cache["Data"] ~= nil then
               image_data = cache["Data"]
           end
           if cache["Last-Modified"] ~= nil then
               cached_headers["If-Modified-Since"] = cache["Last-Modified"]
           end
           if cache["Etag"] ~= nil then
               cached_headers["If-None-Match"] = cache["Etag"]
           end
        file:close()
    end
    return image_data, cached_headers
end
function imgui.ImageURL:download(url, preload_cache)
    local st = self.download_statuses
    self.pool[url] = {
        status = st.DOWNLOADING,
        image = nil,
        error = nil
    }
    local cached_image, cached_headers = imgui.ImageURL:get_cache(url)
    local img = self.pool[url]
    if preload_cache and cached_image ~= nil then
        img.image = imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
    end
    asyncHttpRequest("GET", url, { headers = cached_headers },
        function(result)
            if result.status_code == 200 then
                img.image = imgui.CreateTextureFromMemory(memory.strptr(result.text), #result.text)
                img.status = st.SAVED
                imgui.ImageURL:set_cache(url, result.text, result.headers)
            elseif result.status_code == 304 then
                img.image = img.image or imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
                img.status = st.NOT_MODIFIED
            else
                img.status = img.image and st.CACHE_ONLY or st.ERROR
                img.error = ("Error #%s"):format(result.status_code)
            end
        end,
        function(error)
            img.status = img.image and st.CACHE_ONLY or st.ERROR
            img.error = error
        end
    )
end
function imgui.ImageURL:render(url, size, preload, ...)
    local st = self.download_statuses
    local img = self.pool[url]
    if img == nil then
        self.pool[url] = {
            status = st.INIT,
            error = nil,
            image = nil
        }
        img = self.pool[url]
    end
    if img.status == st.INIT then
        imgui.ImageURL:download(url, preload)
    end
     
    if img.image ~= nil then
        imgui.Image(img.image, size, ...)
    else
        imgui.Dummy(size)
    end
    return img.status, img.error
end
setmetatable(imgui.ImageURL, {
    __call = imgui.ImageURL.render
})


Lua:
[18:52:05.463200] (error)   urltest.lua: ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:306: attempt to index upvalue 'renderer' (a nil value)
stack traceback:
    ...ames Launcher\bin\arizona\moonloader\lib\mimgui\init.lua:306: in function 'CreateTextureFromFile'
    ...rizona Games Launcher\bin\arizona\moonloader\urltest.lua:44: in main chunk
[18:52:05.463200] (error)   urltest.lua: Script died due to an error. (20A23D14)

Lua:
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local new = imgui.new
local renderWindow = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 700, 500
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow)
        imgui.Image(img, imgui.ImVec2(464, 464)--[[размер]])
        imgui.End()
    end
)
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('urlt', function()
        renderWindow[0] = not renderWindow[0]
    end)
    while true do
        wait(0)
        if not doesFileExist("moonloader/resource/image/exampe.jpg") then
            sampAddChatMessage('[{501c5f}MyRecords{FFFFFF}]: Фото не было найдено, началось автоматическое скачивание, не закрывайте игру!', -1)
            download_id = downloadUrlToFile('https://i.imgur.com/kpopR9i.jpeg', 'moonloader/resource/image/exampe.jpeg', function(id, status, p1, p2)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then sampAddChatMessage('[{501c5f}MyRecords{FFFFFF}]: Скачивание успешно завершено', -1) end
            end)
        end
    end
end
local img = imgui.CreateTextureFromFile(getWorkingDirectory()..'/resource/image/exampe.jpeg')
Если бы открыл свои глазки, увидел бы это:
Зависимости:
1) Функция асинхронных запросов (effil)

Код с функцией-зависимостью:
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local new = imgui.new
local renderWindow = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow)
        imgui.ImageURL("https://items.shinoa.tech/images/model/2296.png", imgui.ImVec2(256, 256), true)
        imgui.End()
    end
)
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('urlt', function()
        renderWindow[0] = not renderWindow[0]
    end)
    while true do
        wait(0)
      
    end
end
function handleAsyncHttpRequestThread(runner, resolve, reject)
  local status, err
  repeat
    status, err = runner:status()
    wait(0)
  until status ~= 'running'
  if not err then
    if status == 'completed' then
      local result, response = runner:get()
      if result then
        resolve(response)
      else
        reject(response)
      end
      return
    elseif status == 'canceled' then
      return reject(status)
    end
  else
    return reject(err)
  end
end

function asyncHttpRequest(method, url, args, resolve, reject)
  assert(type(method) == 'string', '"method" expected string')
  assert(type(url) == 'string', '"url" expected string')
  assert(type(args) == 'table', '"args" expected table')
  local thread = requestRunner()(method, url, encodeJson(args))
  if not resolve then resolve = function() end end
  if not reject then reject = function() end end
 
  return {
    effilRequestThread = thread;
    luaHttpHandleThread = lua_thread.create(handleAsyncHttpRequestThread, thread, resolve, reject);
  }
end
local md5 = require "md5"
imgui.ImageURL = {
    cache_dir = getWorkingDirectory() .. "/resource/cache",
    download_statuses = {
        INIT = 0,
        DOWNLOADING = 1,
        ERROR = 2,
        SAVED = 3,
        NOT_MODIFIED = 4,
        CACHE_ONLY = 5
    },
    pool = {}
}
function imgui.ImageURL:set_cache(url, image_data, headers)
    if not doesDirectoryExist(self.cache_dir) then
        createDirectory(self.cache_dir)
    end
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    local file, err = io.open(path, "wb")
    if not file then
        return nil
    end
    local data = { Data = tostring(image_data) }
    if headers["etag"] then
        data["Etag"] = headers["etag"]
    end
    if headers["last-modified"] then
        data["Last-Modified"] = headers["last-modified"]
    end
    file:write(encodeJson(data))
    file:close()
    return path
end
function imgui.ImageURL:get_cache(url)
    local path = ("%s/%s"):format(self.cache_dir, md5.sumhexa(url))
    if not doesFileExist(path) then
        return nil, nil
    end
    local image_data = nil
    local cached_headers = {}
    local file, err = io.open(path, "rb")
    if file then
        local cache = decodeJson(file:read("*a"))
        if type(cache) ~= "table" then
            return nil, nil
        end
        if cache["Data"] ~= nil then
               image_data = cache["Data"]
           end
           if cache["Last-Modified"] ~= nil then
               cached_headers["If-Modified-Since"] = cache["Last-Modified"]
           end
           if cache["Etag"] ~= nil then
               cached_headers["If-None-Match"] = cache["Etag"]
           end
        file:close()
    end
    return image_data, cached_headers
end
function imgui.ImageURL:download(url, preload_cache)
    local st = self.download_statuses
    self.pool[url] = {
        status = st.DOWNLOADING,
        image = nil,
        error = nil
    }
    local cached_image, cached_headers = imgui.ImageURL:get_cache(url)
    local img = self.pool[url]
    if preload_cache and cached_image ~= nil then
        img.image = imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
    end
    asyncHttpRequest("GET", url, { headers = cached_headers },
        function(result)
            if result.status_code == 200 then
                img.image = imgui.CreateTextureFromMemory(memory.strptr(result.text), #result.text)
                img.status = st.SAVED
                imgui.ImageURL:set_cache(url, result.text, result.headers)
            elseif result.status_code == 304 then
                img.image = img.image or imgui.CreateTextureFromMemory(memory.strptr(cached_image), #cached_image)
                img.status = st.NOT_MODIFIED
            else
                img.status = img.image and st.CACHE_ONLY or st.ERROR
                img.error = ("Error #%s"):format(result.status_code)
            end
        end,
        function(error)
            img.status = img.image and st.CACHE_ONLY or st.ERROR
            img.error = error
        end
    )
end
function imgui.ImageURL:render(url, size, preload, ...)
    local st = self.download_statuses
    local img = self.pool[url]
    if img == nil then
        self.pool[url] = {
            status = st.INIT,
            error = nil,
            image = nil
        }
        img = self.pool[url]
    end
    if img.status == st.INIT then
        imgui.ImageURL:download(url, preload)
    end
      
    if img.image ~= nil then
        imgui.Image(img.image, size, ...)
    else
        imgui.Dummy(size)
    end
    return img.status, img.error
end
setmetatable(imgui.ImageURL, {
    __call = imgui.ImageURL.render
})