简体   繁体   English

使用 JavaScript 从 URL 转换和下载图像

[英]transform and download a image from URL using JavaScript

I'm having a huge problem.我有一个大问题。 I'm trying to download a scaled and rendered image using these CSS properties:我正在尝试使用这些 CSS 属性下载缩放和渲染图像:

 transform: scale(2); image-rendering: pixelated;

Which will result to this:这将导致:

 <img style="margin:15px 15px; transform: scale(2); image-rendering:pixelated;" src="https://images.habbo.com/c_images/album1584/FAS03.png">

As you would know if I tried to save the image it wouldn't save with the applied CSS properties and saves as the original dimensions.如您所知,如果我尝试保存图像,它不会使用应用的 CSS 属性保存并保存为原始尺寸。 Is there any way I can apply these properties and then download the image like it is displayed above using the CSS properties?有什么方法可以应用这些属性,然后使用 CSS 属性下载上面显示的图像?

I'm basically trying to scale the image without losing quality and download it scaled.我基本上是想在不损失质量的情况下缩放图像并下载缩放后的图像。 I can't just save the image and resize it because it will become very blurry.我不能只保存图像并调整它的大小,因为它会变得非常模糊。

I tried using html2canvas but failed here is the link to the codepen: https://codepen.io/Ownslo/pen/XWdgByY我尝试使用 html2canvas 但失败了这里是代码笔的链接: https://codepen.io/Ownslo/pen/XWdgByY

^ but I'm pretty sure using that would just scale the image and not render it making it blurry. ^ 但我很确定使用它只会缩放图像而不是渲染它使其变得模糊。 (but for some odd reason it doesn't even download the image correctly and downloads a all white image.) (但由于某些奇怪的原因,它甚至没有正确下载图像并下载全白图像。)

Hopefully someone can help me out.希望有人能帮助我。 Thank you.谢谢你。

Try loading your image into a Canvas and doing all your image modifications on the 2d context.尝试将图像加载到 Canvas 并在 2d 上下文中进行所有图像修改。 I made you an example here:我在这里给你举了个例子:

https://jsfiddle.net/mortac8/mhds8wn6/1/ https://jsfiddle.net/mortac8/mhds8wn6/1/

<canvas id="mycanvas" height=100 width=100></canvas>

<script>
  let download = function(){
    let link = document.createElement('a');
    link.download = 'anAnswer.png';
    link.href = document.getElementById('mycanvas').toDataURL();
    link.click();
  }

  let img = new Image();
  img.src = "https://images.habbo.com/c_images/album1584/FAS03.png";
  img.setAttribute("crossorigin", "anonymous");
  img.addEventListener("load", function() {
    let canvas = document.getElementById("mycanvas");
    let ctx = canvas.getContext("2d");
    ctx.scale(2,2);
    ctx.imageSmoothingEnabled = false;
    ctx.drawImage(img, 0, 0);
    download();
  });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM