I am writing an addon in firefox that automatically sends the contents of a canvas to imgur. I have already built a similar extension in chrome, where it works as expected, so I know that the usage of imgurs API is correct. When I use the same approach in the Firefox addon, I always get this response:
{
"data": {
"error": "Image format not supported, or image is corrupt.",
"request": "/3/upload",
"method": "POST"
},
"success": false,
"status": 400
}
This is what I use to extract the image data and send it to the imgur API:
Request({
url: 'https://api.imgur.com/3/upload',
contentType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();
and this is used to get a selection from a canvas and get the dataurl of that selection:
function getImageSelection(type) {
//Create copy of cropped image
var mainImageContext = mainImage.getContext('2d');
var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);
var newCanvas = tabDocument.createElement("canvas");
newCanvas.width = selection.w;
newCanvas.height = selection.h;
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
return mainImage.toDataURL(type)
}
I have tried everything: using the dataurl from the original canvas (mainImage), getting the dataUrl without any type, this: .replace(/^data:image\/(png|jpg);base64,/, "");
But imgur keeps complaining about bad format.
In the end, it turned out that the usage of the Request module of the Firefox addon SDK was wrong.
Instead of using contentType
to provide the type of the content (like in jquery/ajax), you have to use dataType
. See below:
Request({
url: 'https://api.imgur.com/3/upload',
dataType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg', true)
},
onComplete: function (response) {
response = JSON.parse(response.text);
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();