Resize an image

I took some code that I posted back in 2016 to resize images and made it a little better. The reSize() function takes 3 parameters. The first parameter is the new width, the second the new height, and the third the image to resize. If the second variable (the new height) is set to 0, then the image will be resized using just the width value but keeping the width to height ratio of the original image. The function returns the resized image.

You can use the example below to change the resize values to see the resizing of the Cargo Bot startup screen. The original image is shown with the resized image overlaying it.

viewer.mode=FULLSCREEN

function setup()
    img=readImage(asset.builtin.Cargo_Bot.Startup_Screen)
    newImage=reSize(150,0,img)
end

function draw()
    background(40, 40, 50)
    sprite(img,WIDTH/2,HEIGHT/2)  
    sprite(newImage,200,400)
end

function reSize(sizeX,sizeY,img)
    pushStyle()
    noSmooth()
    local iw,ih=img.width*(sizeX/img.width),0
    if sizeY==0 then    -- keep width to height ratio
        ih=img.height*(sizeX/img.width)
    else
        ih=img.height*(sizeY/img.height)
    end
    local temp=image(iw,ih)
    setContext(temp)
    sprite(img,iw/2,ih/2,iw,ih)
    setContext() 
    popStyle()
    return temp       
end

the docs seem to say nosmooth only affects lines. is that not the case?

@RonJeffries As far as I know, noSmooth works for anything. NoSmooth means that the transition from one color to the next will be exact. There won’t be a soft transition. If you want to know for sure, I’ll write some code and verify what I’m saying. Stay tuned.

noSmooth() works on rects and ellipses. I don’t think you can take a picture and do noSmooth to sharpen it. I’ll see if resizing a picture with noSmooth changes it.

@RonJeffries thanks for catching this, updated documentation for next version https://codea.io/reference/Graphics.html#noSmooth

thanks!