【问题标题】:How to achieve high quality cropped images from canvas?如何从画布上实现高质量的裁剪图像?
【发布时间】:2016-11-23 21:55:42
【问题描述】:

我正在拼命寻找一个好的裁剪工具。那里有一堆,例如:

Croppic

Cropit

Jcrop

我想要找到的最重要的东西是裁剪工具,它可以裁剪图像而不会降低裁剪图像的分辨率。您可以通过调整图像大小来使用画布标签来解决这个问题。这样图像本身就保持原生,只有表示更小。 DarkroomJS 也是解决方案附近的东西,但不幸的是,下载的演示不起作用。我会试着找出问题所在。有人知道一些很好的替代方案,或者如何让裁剪后的图像...比如说“原生”分辨率?

提前致谢!

【问题讨论】:

  • 它们都返回图像的原始分辨率,减去裁剪的像素,所以我对你的意思有点困惑。您能否提供一个显示问题的示例图像,以及您期望结果的图像,以便我们了解问题所在。
  • 嗨盲人!感谢您的评论。回复in Jcrop 时出现问题。我现在正在使用cropit。我的意思是,裁剪后的图像取决于“图像预览”窗口的大小。如果我有一张大图片,比如 1920x1080 像素,我想裁剪一个选定区域,而我的“图像预览”窗口是 40x40 像素,我将得到一个 40x40 像素的图像,即使该区域类似于例如500x500 像素。有没有办法通过更小的图像预览尺寸来实现这个 500x500 像素?

标签: image canvas crop


【解决方案1】:

您依靠裁剪工具为用户提供界面。问题是返回的图像大小适合界面而不是原始图像。而不是我筛选各种 API 来查看它们是否提供了某种控制这种行为的方法(我假设至少其中一些会),因为这是一个如此简单的过程,我将展示如何手动裁剪图像。

以 JCrop 为例

jcrop为cropstart、cropmove、cropend提供了各种事件……你可以添加一个监听器来监听这些事件,并保留一份当前裁剪界面状态的副本

var currentCrop;    
jQuery('#target').on('cropstart cropmove cropend',function(e,s,crop){
    currentCrop = crop;
}

我不知道你在哪里设置了界面大小,我假设事件返回界面比例的裁剪细节

var interfaceSize = { //you will have to work this out
     w : ?,
     h : ?.
}

你的原图

var myImage = new Image(); // Assume you know how to load 

因此,当单击裁剪按钮时,您可以通过将裁剪细节缩放回原始图像大小来创建新图像,以裁剪大小创建画布,绘制图像以正确定位裁剪区域并返回画布原样或作为新图像。

// image = image to crop
// crop = the current cropping region
// interfaceSize = the size of the full image in the interface
// returns a new cropped image at full res
function myCrop(image,crop,interfaceSize){
     var scaleX = image.width / interfaceSize.w; // get x scale
     var scaleY = image.height / interfaceSize.h; // get y scale
     // get full res crop region. rounding to pixels
     var x = Math.round(crop.x * scaleX);
     var y = Math.round(crop.y * scaleY);
     var w = Math.round(crop.w * scaleX);
     var h = Math.round(crop.h * scaleY);
     // Assume crop will never pad
     // create an drawable image
     var croppedImage = document.createElement("canvas");
     croppedImage.width = w;
     croppedImage.height = h;
     var ctx = croppedImage.getContext("2d");
     // draw the image offset so the it is correctly cropped
     ctx.drawImage(image,-x,-y);
     return croppedImage
}

然后你只需要在点击裁剪按钮时调用这个函数

var croppedImage;
myButtonElement.onclick = function(){
    if(currentCrop !== undefined){ // ensure that there is a selected crop
        croppedImage = myCrop(myImage,currentCrop,interfaceSize);             
    }
}

您可以将图片转换为dataURL以供下载,并通过

imageData = croppedImage.toDataURL(mimeType,quality) // quality is optional and only for "image/jpeg" images

【讨论】:

  • 感谢盲人的回复,非常感谢。我会尝试一下,如果有其他需要知道的,我会回来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
相关资源
最近更新 更多