Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resizing an Image? #1271

Closed
JonasJW opened this issue Oct 5, 2018 · 2 comments
Closed

Resizing an Image? #1271

JonasJW opened this issue Oct 5, 2018 · 2 comments

Comments

@JonasJW
Copy link

JonasJW commented Oct 5, 2018

Issue or Feature

Is it possible to resize a Image? In the browser I can change a ImageElement like the following code. However in node it wont change the size and the image and therefore the canvas still have the original size of 500x375 (in my case).

Steps to Reproduce

const fs = require('fs');
const Canvas = require('canvas');
const Image = Canvas.Image

fs.readFile('./model/pic.jpg', (err, data) => {
    img = new Image;
    img.src = data;

    if (img.width > img.height) {
        img.height = 224;
    } else {
        img.width = 224;
    }

    const canvas = new Canvas(img.width, img.height);
    const ctx = canvas.getContext('2d');

    ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
})

Your Environment

  • Version of node-canvas: 1.6.12
  • Environment Mac High Sierra
@zbjornson
Copy link
Collaborator

See #848 -- this is missing from node-canavs. img.height= does nothing (unless you're using SVG with v2.x, IIRC). However, drawImage() does work to scale images; you'll just need to figure out the scaling factor to use instead of being able to set the width/height in pixels.

(Also, you should put the code that depends on the img into an img.onload handler. Right now img.src= is synchronous, but it's not supposed to be and will hopefully become async in the future.)

@rhengles
Copy link

rhengles commented Sep 14, 2021

I'm having a similar problem. I have successfully drawn an resized SVG file in my canvas.

However, when I try to draw a PNG image, it is not being resized, it is only drawn at the PNG native size.

I'm right now trying to compile from source to see if this solves my problem.

Edit: No, even compiling from source did not solve the issue. This is the code I'm using:

	const { loadImage } = Canvas
	const image = await loadImage("/path/to/image.png")
	// native png image dimensions: 2216 x 1600
	image.width = 680
	image.height = 491

	ctx.drawImage(image, 1200, 924.5, 680, 491)

Edit 2: The solution was to use transforms on the canvas.

	ctx.save()
	ctx.translate(1200, 924.5)
	ctx.scale(680 / 2216, 491 / 1600)
	ctx.drawImage(image, 0, 0)
	ctx.restore()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants