上传Cloudinary后如何裁剪图像?

How to crop image after upload Cloudinary?

我如何在上传后裁剪图片并将编辑后的响应 url 发送到前端? 我将不胜感激

我的代码:

const stream = cloudinary.uploader.upload_stream(
  {
    folder,
  },
  (error: UploadApiErrorResponse | undefined, result: UploadApiResponse | undefined): void => {
    console.log(error, result)
    if (result) {
      resolve({
        url: result.url,
        size: Math.round(result.bytes / 1024),
        height: result.height,
        width: result.width,
      })
    } else {
      reject(error)
    }
  }
)

streamifier.createReadStream(buffer).pipe(stream)

最常见的集成 Cloudinary 的方法是将原始文件上传到您的 Cloudinary 帐户并将上传 API 响应存储到您的数据库,其中包含图像的详细信息:https://cloudinary.com/documentation/image_upload_api_reference#sample_response

如果您不想存储整个响应,您应该至少存储稍后为该图像创建 URL 所需的字段:https://cloudinary.com/documentation/image_transformations#transformation_url_structure

(即 public_idresource_typetypeformattimestamp)虽然严格来说,如果您的assets 是 'upload' 类型的图片——不过你当然需要 public_id。

然后,在您的前端代码中,当将图像添加到您的页面或应用程序时,您在构建 URL 时添加转换参数,要求返回图像并应用转换以匹配它where/how 您正在使用图片。

一个常见的选项是将宽度和高度设置为与图像标签或图像视图完全匹配,然后在原始纵横比不匹配时应用自动裁剪,裁剪选择是自动的:https://cloudinary.com/documentation/resizing_and_cropping

一个Javascript例子来添加那些参数,如果图像应该是500x500是:

cloudinary.url( public_id,
  {
   resource_type: 'image', //these are the defaults and can be ommitted
   type: 'upload', //these are the defaults and can be ommitted
   height: 500,
   width: 500,
   crop: 'lfill', // try to fill the requested width and height without scaling up, crop if needed
   gravity: 'auto', // select which area to keep automatically
   fetch_format: 'auto',
   quality: 'auto',
   format: 'jpg',  // sets the file extension on the URL, and will convert to that format if needed, and no fetch_format was set to override that
  });

结果 URL 将类似于:http://res.cloudinary.com/demo/image/upload/c_lfill,f_auto,g_auto,h_500,q_auto,w_500/sample.jpg