Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- BMP Image Viewer for CraftOS-PC with URL support
- local function downloadImage(url)
- shell.run("wget", url, "temp.bmp")
- if not fs.exists("temp.bmp") then
- error("Failed to download image")
- end
- end
- local function readBMP(path)
- local file = fs.open(path, "rb")
- if not file then error("Failed to open file") end
- local header = file.read(54)
- local width = string.unpack("<I4", header:sub(19, 22))
- local height = string.unpack("<I4", header:sub(23, 26))
- local bpp = string.unpack("<I2", header:sub(29, 30))
- if bpp ~= 24 then error("Only 24-bit BMPs supported") end
- local pixels = {}
- local padding = (4 - ((width * 3) % 4)) % 4
- for y = height-1, 0, -1 do
- pixels[y] = {}
- for x = 0, width-1 do
- local b, g, r = file.read(1):byte(), file.read(1):byte(), file.read(1):byte()
- pixels[y][x] = {r, g, b}
- end
- file.read(padding)
- end
- file.close()
- return {width=width, height=height, pixels=pixels}
- end
- local function displayBMP(bmp)
- term.setGraphicsMode(2) -- Set 256-color mode
- for y = 0, bmp.height-1 do
- for x = 0, bmp.width-1 do
- local r, g, b = table.unpack(bmp.pixels[y][x])
- local color = bit32.bor(bit32.lshift(r, 16), bit32.lshift(g, 8), b)
- term.setPixel(x, y, color)
- end
- end
- end
- -- Main program
- local args = {...}
- if #args < 1 then
- print("Usage: bmpviewer <filename or URL>")
- return
- end
- local path = args[1]
- if path:match("^https?://") then
- downloadImage(path)
- path = "temp.bmp"
- end
- local bmp = readBMP(path)
- displayBMP(bmp)
- -- Clean up temporary file
- if fs.exists("temp.bmp") then
- fs.delete("temp.bmp")
- end
- -- Wait for key press before exiting
- os.pullEvent("key")
- term.setGraphicsMode(0) -- Return to text mode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement