RED
RED

Reputation: 39

Crop image to canvas

I have 2 divs

<div id="image-orig">
    <img src="image_example.jpg"/>
</div>

<div id="image-crop">
    <canvas id="preview" style="width:548px;height:387px"></canvas>
</div>

image_example.jpg can be image any size.

    function updatePreview(c) {
        if(parseInt(c.w) > 0) {
            var orig = $("#image-orig img")[0];
            var canvas = $("#image-crop canvas")[0];
            var context = canvas.getContext("2d");

            context.drawImage(orig,
                c.x*coeff,c.y*coeff,c.w*coeff,c.h*coeff,
                0,0,canvas.width,canvas.height
            );
        }
     }

    $(function(){
            $('#image-orig img').Jcrop({
                onSelect: updatePreview,
                onChange: updatePreview,
                aspectRatio : parseFloat($('#image-orig img').width()/$('#image-orig img').height())
            });
    });

coeff - it's coefficient if size image larger div preview.

That's problem: http://dbwap.ru/3725988.png

In second div (canvas). Quality image very low.

SOLUTION IS FOUND

            canvas.width = c.w*coeff;
            canvas.height = c.h*coeff;

            context.drawImage(orig,
                c.x*coeff,c.y*coeff,c.w*coeff,c.h*coeff,
                0,0,c.w*coeff,c.h*coeff
            );
            $(that.el).find("#ImageCode").attr('src', canvas.toDataURL());
            $(that.el).find("#ImageCode").show();

I'm just creating image tag and copying from canvas to image.

Upvotes: 1

Views: 2563

Answers (1)

BumbleB2na
BumbleB2na

Reputation: 10763

If you have access to .net, you can modify the way your new images are saved with JCrop: http://mironabramson.com/blog/post/2009/04/Cropping-image-using-jQuery,-Jcrop-and-ASPNET.aspx

Solution available to you without using server-side (.net / php):

First, make sure that when you use JCrop that you have html5 canvas image smoothing enabled:

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html

If that is already set, or has no effect, then I think your only other options to investigate image option available to you through each browser:

Enable smoothing in Mozilla - See this article as an example (look for 'mozImageSmoothingEnabled'):https://developer.mozilla.org/en/Canvas_tutorial/Using_images#Controlling_image_scaling_behavior

Apply filters in IE: http://code.flickr.com/blog/2008/11/12/on-ui-quality-the-little-things-client-side-image-resizing/

Note: There may be some sort of Flash solution that could work but it would probably be too difficult to combine any Flash solution with JCrop and html5 canvas.

Upvotes: 1

Related Questions