简体   繁体   English

如何正确获得裁剪图像长度?

[英]How to get cropped image length correctly?

I want to crop an uploaded image with this code . 我想使用此代码裁剪上传的图像。

also, I want to limit the size of the image (in byte) and save it as png format. 另外,我想限制图像的大小(以字节为单位)并将其保存为png格式。 when I don't use of the cropped image, I can get image length using this code: 当我不使用裁剪的图像时,我可以使用以下代码获取图像长度:

var postedFile = Request.Files["FileUpload1"];
long length=postedFile.ContentLength;

my problem is that I can not get the cropped image length correctly. 我的问题是我无法正确获得裁剪的图像长度。 if I use bytes.Length in Upload function, it gets me the length greater than the original image length from FileUpload control. 如果我在Upload函数中使用bytes.Length ,它bytes.Length我的长度大于FileUpload控件的原始图像长度。 how can get cropped image length in png format? 如何以png格式获取裁剪的图像长度?

my code is as follows: 我的代码如下:

    <script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> 
    </script>
    <script type="text/javascript" src="http://jcrop- 
    cdn.tapmodo.com/v0.9.8/js/jquery.Jcrop.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#FileUpload1').change(function () {
                $('#Image1').hide();
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#Image1').show();
                    $('#Image1').attr("src", e.target.result);
                    $('#Image1').Jcrop({
                        onChange: SetCoordinates,
                        onSelect: SetCoordinates
                    });
                }
                reader.readAsDataURL($(this)[0].files[0]);
            });

            $('#btnCrop').click(function () {
                var x1 = $('#imgX1').val();
                var y1 = $('#imgY1').val();
                var width = $('#imgWidth').val();
                var height = $('#imgHeight').val();
                var canvas = $("#canvas")[0];
                var context = canvas.getContext('2d');
                var img = new Image();
                img.onload = function () {
                    canvas.height = height;
                    canvas.width = width;
                    context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
                    $('#imgCropped').val(canvas.toDataURL());
                    $('[id*=btnUpload]').show();
                };
                img.src = $('#Image1').attr("src");
            });
        });
        function SetCoordinates(c) {
            $('#imgX1').val(c.x);
            $('#imgY1').val(c.y);
            $('#imgWidth').val(c.w);
            $('#imgHeight').val(c.h);
            $('#btnCrop').show();
        };
    </script>

    <input type="file" id="FileUpload1" name="FileUpload1"  />
    <br />
    <br />
    <table border="0"  cellpadding="0" cellspacing="5" style="text-align:right">
     <tr >
     <td>
     <img id="Image1" alt="" style="display: none" />
     <br />
     <canvas id="canvas" height="5" width="5"></canvas>
     </td>
     </tr>
    </table>
    <br />
     <input type="button" class="button" id="btnCrop" value="crop" style="display: none" />
     <asp:Button ID="btnUpload" CssClass="button" runat="server" Text="upload" OnClick="Upload" Style="display: none" />
     <input type="hidden" name="imgX1" id="imgX1" />
     <input type="hidden" name="imgY1" id="imgY1" />
     <input type="hidden" name="imgWidth" id="imgWidth" />
     <input type="hidden" name="imgHeight" id="imgHeight" />
     <input type="hidden" name="imgCropped" id="imgCropped" />

and in code behinde: 并在代码behinde:

    var postedFile = Request.Files["FileUpload1"];
    if (postedFile != null && postedFile.ContentLength > 0)
    {
        string filename = postedFile.FileName;
        FileInfo fi = new FileInfo(filename);
        string ext = fi.Extension;
        if (ext != ".png")
         {
            lblMessage.Text = "please upload .png file";
             return;
         }
         long length=postedFile.ContentLength;//this line return original length correctly
         string base64 = Request.Form["imgCropped"];
         byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
         int length= bytes.Length //get copped image length, but it greater than orig size
         using (System.IO.FileStream stream = new System.IO.FileStream(path + "\\" + filename, System.IO.FileMode.Create))
         {
              stream.Write(bytes, 0, bytes.Length);
              stream.Flush(); 
         }

update: I try canvas.toDataURL() in different quality (1,0.95,...) and png and jpeg format and check the cropped image length when selecting the whole of the image, but this length differs from the original image. 更新:我尝试不同质量(1,0.95,...)和png和jpeg格式的canvas.toDataURL(),并在选择整个图像时检查裁剪的图像长度,但此长度与原始图像不同。 (I want to get length 75% of the original length if I select 75% pixels of the original image in the cropped image.) what is the reason and what is value to be set to quality and format to get the same quality as the original image? (如果我在裁剪后的图像中选择原始图像的75%像素,我希望得到原始长度的75%。)原因是什么,设置质量和格式的价值是什么,以获得与原始图像?

Your problem is not that you are getting the length incorrectly , rather it is that you are compressing your cropped image with higher quality settings than the original image you cropped. 您的问题不在于您的长度不正确 ,而在于您使用比裁剪的原始图像更高的质量设置来压缩裁剪的图像。

Consider explicitly setting format and quality options for .toDataURL 考虑明确设置.toDataURL格式和质量选项

If you want you can use the same settings as the original file, which should result in a smaller file if the dimensions are smaller (except possibly for very tiny images where header sizes dominate.) 如果需要,可以使用与原始文件相同的设置,如果尺寸较小,则应该生成较小的文件(除非标题尺寸占主导地位的非常小的图像。)

The default type is image/png and the default quality value is 0.92 , which could be the reason that a smaller image (because you cropped it a little bit) could be of a larger file size than the original uncropped image; 默认类型是image/png ,默认质量值为0.92 ,这可能是因为较小的图像(因为您将其略微裁剪)可能比原始未剪切图像的文件大小更大; because the cropped image was encoded using higher quality settings than your source image. 因为裁剪后的图像使用的质量设置比源图像更高。

For example, if the amount of cropping results in the cropped image being 75% of the number of pixels of the original, but those pixels are then encoded using a scheme that uses (on average) 2 times the number of bytes as the original encoding, then the cropped file will be approximately 150% of the length original. 例如,如果裁剪图像的裁剪量导致裁剪图像的数量为原始像素数量的75% ,则使用(平均) 2倍字节数作为原始编码的方案对这些像素进行编码,然后裁剪的文件大约是原始长度的150%。 I provide this example to illustrate how it is possible for cropped file to have a larger file size than the uncropped file. 我提供此示例来说明裁剪文件如何比未裁剪文件具有更大的文件大小。

Exerpt from the documentation for canvas.toDataURL : 从canvas.toDataURL 的文档中canvas.toDataURL

 canvas.toDataURL(type, encoderOptions); 

type (Optional) A DOMString indicating the image format. type (可选)指示图像格式的DOMString。 The default format type is image/png. 默认格式类型为image / png。

encoderOptions (Optional) A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. encoderOptions (可选)0到1之间的数字,表示用于使用有损压缩的图像格式(如image / jpeg和image / webp)的图像质量。 If this argument is anything else, the default value for image quality is used. 如果此参数为其他参数,则使用图像质量的默认值。 The default value is 0.92. 默认值为0.92。 Other arguments are ignored. 其他参数被忽略。

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

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