Matt
Matt

Reputation: 1257

Saving DataURL to jpg

I have the following code that turns an image file(jpg/png) to data url. Once cropping has been done, I can generate a rendered image, but it is saved as png. I need to be able to save the data url as a jpg.

renderButton.click(function (event) {
var dataUrl;

imgly.renderToDataURL("png", { size: "1280" }, function (err, dataUrl) {

var image = $("<img><br>").attr({
    src: dataUrl
  });

  image.appendTo($(".result"))
  $button = $('<button class="btn btn-default remove">')
        .text('Remove')
        .on('click', function () {
            image.remove();
            $(this).remove();
            return false;
        });
    $button.appendTo($(".result"));;

    });
});

Changing "png" to "jpg" in the renderToDataURL line has no affect. Any ideas?

Upvotes: 2

Views: 4620

Answers (2)

Yuda Zvi
Yuda Zvi

Reputation: 29

DataURL is just a string, so you can replace the "png" with "jpeg"

const jpegImg = pngImg.replace("png", "jpeg")

Upvotes: -1

invernomuto
invernomuto

Reputation: 10211

change your call to

imgly.renderToDataURL("image/jpeg", { size: "1280" }, function (err, dataUrl)

how you can read from source code

renderToDataURL: (format, options={}, callback) ->
    if typeof options is "function"
      callback = options
      options = {}

@photoProcessor.renderImage options, (err, imageData) =>
      canvas = Utils.newCanvasFromImageData imageData
      callback null, canvas.toDataURL(format)

where format is the image format, the canvas.toDataURL(format) is the responsible of data translation

The problem was the MIME Type, how you can read from the spec

When the toDataURL(type) method is called with one or more arguments, it must return a data: URL containing a representation of the image in the format given by type. The possible values are MIME types with no parameters, for example image/png, image/jpeg, or even maybe image/svg+xml if the implementation actually keeps enough information to reliably render an SVG image from the canvas.

EDIT

renderButton.click(function (event) {
var dataUrl;

imgly.renderToDataURL("image/jpeg", { size: "1280" }, function (err, dataUrl) {

var image = $("<img><br>").attr({
    src: dataUrl
  });

  image.appendTo($(".result"))
  $button = $('<button class="btn btn-default remove">')
        .text('Remove')
        .on('click', function () {
            image.remove();
            $(this).remove();
            return false;
        });
    $button.appendTo($(".result"));;

    });
});

this should work

Upvotes: 3

Related Questions