Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Resize an image

dave1707dave1707 Mod
in Code Sharing Posts: 9,109

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

Comments

  • Posts: 977

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

  • dave1707dave1707 Mod
    edited April 30 Posts: 9,109

    @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.

  • SimeonSimeon Admin Mod
    Posts: 5,587

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

  • Posts: 977

    thanks!

Sign In or Register to comment.