【问题标题】:save image from canvas without increasing its size从画布保存图像而不增加其大小
【发布时间】:2015-11-23 16:49:46
【问题描述】:

我有一个网站,人们可以在其中上传图像并在将它们上传到服务器之前对其进行裁剪。 我的问题是每个图像大小在上传过程中增加了百分之百。比如我拍一张102kb 640x640的JPG图片,当它从网站加载时,我在创建缓存后使用chrome网络工具,看到它的大小是800kb(在我将其保存为 600x600 尺寸后)。 为了将其保存到数据库中,我使用 HTML5 画布并使用 http://fengyuanchen.github.io/cropper/ 进行裁剪 在服务器端,我使用 Azure CloudBlockBlob。

客户:

  VData = $("#uploadedImage").cropper('getCroppedCanvas', {
            width: 600,
            height: 600
        }).toDataURL();

服务器:

public PhotoInfo UploadPhoto(string image, string picCaption)
    {
        string base64 = image.Substring(image.IndexOf(',') + 1);
        byte[] imageByte = Convert.FromBase64String(base64);
        Stream stream = new MemoryStream(imageByte);
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.AppSettings.Get("StorageConnectionString"));

        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference("photos");
        if (container.CreateIfNotExists())
        {
            // configure container for public access
            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);
        }

        // Retrieve reference to a blob 
        string uniqueBlobName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension("blob")).ToLowerInvariant();
        CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
        //blob.Properties.ContentType = image.ContentType;
        blob.Properties.ContentType = "image/jpg";

        stream.Position = 0;
        blob.UploadFromStream(stream);

        var photo = new PhotoInfo()
        {
            ImagePath = blob.Uri.ToString(),
            InvitationId = 0,
            Name = picCaption != null ? picCaption : ""
        };

        PhotoInfo uploadedPhoto = _boxItemProvider.SetPhoto(photo);

        return uploadedPhoto;
    }

这里有什么建议吗?

谢谢。

【问题讨论】:

  • 我对“cropper”一无所知,但是否有设置(降低)jpg 质量的开关?
  • 也不知道“cropper”,但您似乎确实上传了图片的 png 版本。解决方案是先将画布保存为 jpeg,甚至按照@markE 的建议使用0-1 质量参数,如果这还不够,您甚至可以尝试transform your base64 string back to a blob,节省大约 37%数据的大小。如果“cropper”没有这些选项,你可以直接调用cropper canvas'toDataURL("image/jpeg", quality)方法。

标签: javascript c# image canvas html5-canvas


【解决方案1】:

问题已解决! 而不是只使用不带参数的toDataURL(),而是将其替换为toDataURL("image/jpeg", quality),当质量为 1 时,图像大小几乎与原始相同,而当质量为 0.75 时,图像大小减少了 50%

【讨论】:

  • 但它会降低图像质量,我们可以使用与原始图像相同的 MIME 类型并且不改变质量,因此它可能会保持最接近的大小。
猜你喜欢
  • 2013-09-04
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多