I am trying to create an ajax request to my views.py that returns a cropped segment of a larger image. The problem that I am having is that the image doesn't seem to be downloaded, or at least isn't being drawn. There isn't an error message associated with it, just nothing happens (including "test" not being logged to the console). I have left a few of my attempts with the javascript in but none of them seemed to work.
The view function also doesn't appear to be particularly rapid with the 'called' response being printed 5+ seconds after the request. I am wondering if this is because it takes a long time to load the image? If this is the case is there a way to speed this up i.e. to only load the image once and keep it in memory or just a better way of doing it. It is quite a large image (12000x6000px, 28.5 MB JPEG).
I know that the views.py function is being called by confirming it with the logging module.
So in short:
Why is my image not being displayed?
Is there a quicker way of delivering the image?
Views.py:
def test(request):
img = Image.open(settings.STATIC_PATH + 'geogame/big_map.jpg')
img.load()
xpos = int(request.GET.get('xpos', ''))
ypos = int(request.GET.get('ypos', ''))
upper = ypos*10 - 300
left = xpos*10 - 600
right = xpos*10 + 600
lower = ypos*10 + 300
cropped_img = img.crop((left, upper, right, lower))
logging.warn('called')
response = HttpResponse(content_type = 'image/jpg')
img.save(response, "JPEG")
return response
Ajax request:
Game.zoom = function() {
zoomx = Game.clickX
zoomy = Game.clickY
$.ajax({
url: 'zoom/',
data: {xpos: zoomx, ypos: zoomy},
type: 'get',
success: function(data) {
//Game.zoomedImg.src = "data:image/jpg;base64,"+data
//Game.zoomedImg.src = data;
//console.log(Game.zoomedImg.src);
Game.zoomedImg.onload = function() {
console.log("load");
Game.zoomedImg.src = "data:image/jpg;base64,"+data
}
//$("#" + this.zoomedImg).one("load", function() {
// console.log("test");
// Game.ctx.drawImage(Game.zoomedImg, 0, 0);
// }).attr("src", "data:image/jpg;base64,"+data);
//Game.ctx.drawImage(Game.zoomedImg, 0, 0);
console.log("hello");
//};
},
failure: function(data) {
console.log('failed to load zoomed image')
}
});
}
Thanks!
EDIT
buffer = cStringIO.StringIO() logging.warn('egege')
cropped_img.save(buffer, format = "JPEG")
logging.warn('ffgge')
img_str = base64.urlsafe_b64encode(buffer.getvalue())
logging.warn('leflefe')
return HttpResponse(img_str)
Well I believe I have solved both parts
The image needs to be loaded into a string buffer and base64 encoded to be downloaded after being loaded like so:
buffer = cStringIO.StringIO()
cropped_img.save(buffer, format = "JPEG")
img_str = base64.b64encode(buffer.getvalue())
return HttpResponse(img_str)
This is seemingly because the crop action is lazy and needs to be saved before it takes effect.
Also to speed up the process the image load operation and make it a single occurence the following two lines can be moved to the beginning of the views.py file OUTSIDE of the function.
img = Image.open(settings.STATIC_PATH + 'geogame/big_map.jpg')
img.load()
Related
This is a knowledge sharing Q&A.
Cropme is a nice JS add-on for cropping and rotating an image using visual sliders. The author provided good documentation, but building a working implementation is not as simple as it should be.
The question I want to answer is this:
I want to allow my website-users to upload their profile image. That image must be exactly 240x292 pixels. The users should be able zoom and rotate their image, then crop it to that specific size and upload it to my website. How can I do all that with cropme?
These are the requires steps:
Show an empty placeholder for the image we want the user to load.
By clicking the "Get Image" button, the user can select an image from its local files.
The selected file is loaded into memory, and presented for editing using 'cropme'. The user can use visual sliders to rotate and zoom in/out
After clicking "Crop", the user is presented with the cropped image, and can decide to save the image or to cancel.
After clicking "Save", the cropped image is uploaded to a PHP server, the modal window is closed, and the placeholder image is replaced with the link to the just-uploaded image.
So how can we do this?
A fully working demo is presented here:
https://codepen.io/ishahak/pen/XWjVzLr
I will explain some of the details, step by step.
Note: usually in my code when you see obj[0], it is simply a conversion from jQuery object into a simple JS object.
1. Showing a placeholder for the image.
We can create a real SVG image on the fly using this code:
getImagePlaceholder: function(width, height, text) {
//based on https://cloudfour.com/thinks/simple-svg-placeholder/
var svg = '\
<svg xmlns="http://www.w3.org/2000/svg" width="{w}" \
height="{h}" viewBox="0 0 {w} {h}">\
<rect fill="#ddd" width="{w}" height="{h}"/>\
<text fill="rgba(0,0,0,0.5)" font-family="sans-serif"\
font-size="30" dy="10.5" font-weight="bold"\
x="50%" y="50%" text-anchor="middle">{t}</text>\
</svg>';
var cleaned = svg
.replace(/{w}/g, width)
.replace(/{h}/g, height)
.replace('{t}', text)
.replace(/[\t\n\r]/gim, '') // Strip newlines and tabs
.replace(/\s\s+/g, ' ') // Condense multiple spaces
.replace(/'/gim, '\\i'); // Normalize quotes
var encoded = encodeURIComponent(cleaned)
.replace(/\(/g, '%28') // Encode brackets
.replace(/\)/g, '%29');
return 'data:image/svg+xml;charset=UTF-8,' + encoded;
}
2. By clicking the "Get Image" button, the user can select an image from its local files.
This process involves an input element of type "file" which has no visible appearance (we set it with the 'd-none' class), and a button element which 'clicks' it to open a dialog:
<button id="btnGetImage" class="btn btn-primary">Get Image</button>
<input class="d-none" type="file" id="fileUpload" accept="image/*" />
And the relevant code:
$('#btnGetImage').on('click', function(){
//force 'change' event even if repeating same file:
$('#fileUpload').prop("value", "");
$('#fileUpload').click();
});
$('#fileUpload').on('change', function(){
CiM.read_file_from_input(/*input elem*/this, function() {
console.log('image src fully loaded');
$('#imgModal-dialog').modal('show');
});
});
When a file is selected, the 'change' event is firing, leading us to read the file into memory.
3. The selected file is loaded into memory, and presented for editing using 'cropme'. The user can use visual sliders to rotate and zoom in/out
Our read_file_from_input mentioned above is implemented like this:
imgHolder: null,
imgHolderCallback: null,
read_file_from_input: function(input, callback) {
if (input.files && input.files[0]) {
imgHolderCallback = callback;
var reader = new FileReader();
if (!CiM.imgHolder) {
CiM.imgHolder = new Image();
CiM.imgHolder.onload = function () {
if (imgHolderCallback) {
imgHolderCallback();
}
}
}
reader.onload = function (e) {
console.log('image data loaded!');
CiM.imgHolder.src = e.target.result; //listen to img:load...
}
reader.readAsDataURL(input.files[0]);
}
else {
console.warn('failed to read file');
}
}
When the FileReader is ready, we set the src for our internal image holder, and wait for the 'load' event, which signals that the img element is ready with the new content.
We listen to that 'load' event, and when triggered we show the modal. A modal in Bootstrap has several events. We listen to the one which signals that the modal is shown, meaning that the width and set and we can plan our Cropme dimensions based on it.
update_options_for_width: function(w) {
var o = CiM.opt, //shortcut
vp_ratio = o.my_final_size.w / o.my_final_size.h,
h, new_vp_w, new_vp_h;
w = Math.floor(w * 0.9);
h = Math.floor(w / o.my_win_ratio);
o.container.width = w;
o.container.height = h;
new_vp_h = 0.6 * h;
new_vp_w = new_vp_h * vp_ratio;
// if we adapted to the height, but it's too wide:
if (new_vp_w > 0.6 * w) {
new_vp_w = 0.6 * w;
new_vp_h = new_vp_w / vp_ratio;
}
new_vp_w = Math.floor(new_vp_w);
new_vp_h = Math.floor(new_vp_h);
o.viewport.height = new_vp_h;
o.viewport.width = new_vp_w;
}
We wait for the size of the modal to be set because cropme must be set with specific viewport dimensions. At the end of our shown.bs.modal handler, we create our Cropme instance.
4. After clicking "Crop", the user is presented with the cropped image, and can decide to save the image or to cancel.
Here is the save-button handler:
$('#imgModal-btnSave').on('click', function(){
uploadImage(croppedImg[0], function(path_to_saved) {
savedImg[0].src = path_to_saved;
$('#imgModal-dialog').modal('hide');
});
});
The uploadImage function goes like this:
uploadImage: function(img, callback){
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture (needed??)
imgCanvas.width = img.width;
imgCanvas.height = img.height;
// Draw image into canvas element
imgContext.drawImage(img, 0, 0, img.width, img.height);
var dataURL = imgCanvas.toDataURL();
$.ajax({
type: "POST",
url: "save-img.php", // see code at the bottom
data: {
imgBase64: dataURL
}
}).done(function(resp) {
if (resp.startsWith('nok')) {
console.warn('got save error:', resp);
} else {
if (callback) callback(resp);
}
});
}
It is matched with a simple PHP script which appears at the end of the HTML in the codepen. I think this answer went too long, so I'll finish here.
Good luck - have fun :)
I'm trying to load an image from an external URL. The image is retrieved dynamically from a database and is therefore not a direct path. An example of such URL is: http://192.192.168.12:8080/api/imageServer?file=imageName.jpeg. The response in an actual jpeg image; when I add the URL to an image tag or directly in the browser the image is shown. When I try to load the image into Fabric.js I only get the console message "Error loading " without any other message.
This is part of our code:
var updateCanvas = function () {
self.canvas.clear();
if (self.selectedImage() && self.canvas) {
try {
fabric.Image.fromURL(self.selectedImage().imageUrl, function (oImg) {
if (oImg._element == null) {
stickyToast(translations().Error, translations().img_bind_error, "error");
return;
}
self.canvas.clear();
var canvasHeight = 500;
var ratio = canvasHeight / oImg.height;
var canvasWidth = oImg.width * ratio;
//Define all filters that will be used on image
oImg.filters[0] = new fabric.Image.filters.Brightness({
brightness: 0
});
...
I've tried upgrading to the latest version of fabric.js but to no avail. Is there another method I need to use download the image?
I am having a jQuery script that loads 15 images and their hover versions (the hover versions are used when... hovering, not when the page loads). In both Chrome and Firefox in the Network tab, i see this :
images/img1.png
images_hover/img1.png
This must mean the hover images are preloaded correctly, but... when i actually hover and those images are used, they are being loaded again. Here is the preload code :
var prel = new Image();
prel.src = "http://hdodov.byethost15.com/color-game/graphics/parts_hover/" + id + ".png";
I tried using the whole path - http://hdodov.byethost15.com/color-game/graphics/parts_hover/ and the short path too (where the root and the script is) - graphics/parts_hover/. It made no difference.
Could this be caused because my images have the same name? They are in different directories though.
For the next question, you really should paste more code, which makes it easier to help you. I checked your URL you provided, but for other people that might have the same problem, it will be hard to understand what went wrong...
OK, as I said, you are always requesting he images again on hover state...
This worked for me:
var context = new Array(15),
canvas = new Array(15),
canvasNum = -1,
hElem,
hElemPrev,
mousePos = {x:-1, y:-1},
images = [], //<-- Store preloaded images here
imagesHover = []; //<-- Store preloaded images here
... then save them on building like this:
function drawMenuItems(id, width, height){
var canNumHolder, createCanvas;
$('#canvas_holder').append($('<canvas></canvas>')
.attr({
width:width,
height:height,
id:id
})
);
canvasNum++;
canvas[canvasNum] = document.getElementById(id);
context[canvasNum] = canvas[canvasNum].getContext('2d');
canNumHolder = canvasNum;
images[id].crossOrigin = 'Anonymous';
images[id].onload = function(){
context[canNumHolder].drawImage(images[id],0,0);
};
images[id].src = 'graphics/parts/' + id + '.png';
//Hover states
imagesHover[id] = new Image();
imagesHover[id].src = "graphics/parts_hover/" + id + ".png";
}
... give just the id...
function hoverStateChange() {
//....rest of the code
if(hElem >= 0){
drawImageOnCanvas(
canvas[hElem],
context[hElem],
"hover", //pass somethink to checke what you want to do
$(canvas[hElem]).attr('id')
);
//....rest of the code
//change to normal texture
if(hElemPrev >= 0){
drawImageOnCanvas(
canvas[hElemPrev],
context[hElemPrev],
"", //pass empty for other state
$(canvas[hElemPrev]).attr('id')
);
$(canvas[hElemPrev]).removeClass('active');
$('#text_holder').removeClass('a' + hElemPrev);
}
.. and finally
function drawImageOnCanvas(canv, contxt, state, src){
contxt.clearRect(0,0,400,400);
if(state == "hover"){
contxt.drawImage(imagesHover[src],0,0);
}else {
contxt.drawImage(images[src],0,0);
}
}
Like this, you chache you images and not calling them again and again...
I hope it helps.
Yuo can preload images with css like this:-
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
I'm having an issue while using canvas in a background page to create data URLs for desktop notifications' images.
I want to use the "image" notifications which require a 3:2 ratio to display properly. The images I want to use (from hulu.com) are a different ratio, so I decided to use the canvas element to create the corresponding data URL off of these images so that the ratio is correct. It kind of works in theory, but…
…I'm having issues if I'm creating more than one canvas/notification in the background page. One image is created properly, but the rest comes out empty.
Confusingly, opening the same background page in a new tab (i.e. exact same code) makes everything works just fine: all the notifications are created with the images loaded from hulu.com. Also, just changing the dimensions from 360x240 to 300x200 makes it work. Finally, though they're similar computers with the same Chrome version (34.0.1847.116), it works without modification at work while it doesn't on my own laptop.
I made a test extension available at the bottom of this post. Basically, it only has a generated background page. The code for that page is this:
var images = ["http://ib2.huluim.com/video/60376901?size=290x160&img=1",
"http://ib2.huluim.com/video/60366793?size=290x160&img=1",
"http://ib4.huluim.com/video/60372951?size=290x160&img=1",
"http://ib1.huluim.com/video/60365336?size=290x160&img=1",
"http://ib3.huluim.com/video/60376290?size=290x160&img=1",
"http://ib4.huluim.com/video/60377231?size=290x160&img=1",
"http://ib4.huluim.com/video/60312203?size=290x160&img=1",
"http://ib1.huluim.com/video/60376972?size=290x160&img=1",
"http://ib4.huluim.com/video/60376971?size=290x160&img=1",
"http://ib1.huluim.com/video/60376616?size=290x160&img=1"];
for (var i = 0; i < 10; i++) {
getDataURL(i);
}
/*
* Gets the data URL for an image URL
*/
function getDataURL(i) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = 360;
canvas.height = 240;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
var dataURL = canvas.toDataURL('image/png');
chrome.notifications.create('', {
type: 'image',
iconUrl: 'logo_128x128.png',
title: String(i),
message: 'message',
imageUrl: dataURL
}, function(id) {});
}
//img.src = chrome.extension.getURL('logo_128x128.png');;
img.src = images[i];
}
The commented out line for img.src = ... is a test where it loads a local file instead of a remote one. In that case, all the images are created.
The red rectangle added to the canvas is to show that it's not just the remote image that is an issue: the whole resulting canvas is empty, without any red rectangle.
If you download and add the test extension below, you should get 10 notifications but only one with an image.
Then, to open the background page in a new tab, you can inspect the background page, type this in the console:
chrome.extension.getURL('_generated_background_page.html')
and right-click the URL, and click "Open in a new Tab" (or window). Once open you should get 10 notifications that look fine.
Any idea of what is going on? I haven't been able to find any kind of limitations for background pages relevant to that. Any help would be appreciated, because this has been driving me crazy!
Files available here: https://www.dropbox.com/s/ejbh6wq0qixb7a8/canvastest.zip
edit: based on #GameAlchemist's comment, I also tried the following: same getDataURL method, but the loop wrapped inside an onload for the logo:
function loop() {
for (var i = 0; i < 10; i++) {
getDataURL(i);
}
}
var logo = new Image();
logo.onload = function () {
loop();
}
logo.src = chrome.extension.getURL('logo_128x128.png');
Remember that the create() method is asynchronous and you should use a callback with. The callback can invoke next image fetching.
I would suggest doing this in two steps:
Load all the images first
Process the image queue
The reason is that you can utilize the asynchronous image loading better this way instead of chaining the callbacks which would force you to load one and one image.
For example:
Image loader
var urls = ["http://ib2.huluim.com/video/60376901?size=290x160&img=1",
"http://ib2.huluim.com/video/60366793?size=290x160&img=1",
"http://ib4.huluim.com/video/60372951?size=290x160&img=1",
"http://ib1.huluim.com/video/60365336?size=290x160&img=1",
"http://ib3.huluim.com/video/60376290?size=290x160&img=1",
"http://ib4.huluim.com/video/60377231?size=290x160&img=1",
"http://ib4.huluim.com/video/60312203?size=290x160&img=1",
"http://ib1.huluim.com/video/60376972?size=290x160&img=1",
"http://ib4.huluim.com/video/60376971?size=290x160&img=1",
"http://ib1.huluim.com/video/60376616?size=290x160&img=1"];
var images = [], // store image objects
count = urls.length; // for loader
for (var i = 0; i < urls.length; i++) {
var img = new Image; // create image
img.onload = loader; // share loader handler
img.src = urls[i]; // start loading
images.push(img); // push image object in array
}
function loader() {
count--;
if (count === 0) process(); // all loaded, start processing
}
//TODO need error handling here as well
Fiddle with concept code for loader
Processing
Now the processing can be isolated from the loading:
function process() {
// share a single canvas (use clearRect() later if needed)
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
current = 0;
canvas.width = 360;
canvas.height = 240;
createImage(); // invoke processing for first image
function createImage() {
ctx.drawImage(images[current], 0, 0); // draw current image
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
chrome.notifications.create('', {
type : 'image',
iconUrl : 'logo_128x128.png',
title : String(i),
message : 'message',
imageUrl: canvas.toDataURL() // png is default
},
function(id) { // use callback
current++; // next in queue
if (current < images.length) {
createImage(); // call again if more images
}
else {
done(); // we're done -> continue to done()
}
});
}
}
Disclaimer: I don't have a test environment to test Chrome extensions so typos/errors may be present.
Hope this helps!
I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?
I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.
You are right that one can get image dimensions before it's fully loaded.
Here's a solution (demo):
var img = document.createElement('img');
img.src = 'some-image.jpg';
var poll = setInterval(function () {
if (img.naturalWidth) {
clearInterval(poll);
console.log(img.naturalWidth, img.naturalHeight);
}
}, 10);
img.onload = function () { console.log('Fully loaded'); }
The following code returns width/height as soon as it's available. For testing change abc123 in image source to any random string to prevent caching.
There is a JSFiddle Demo as well.
<div id="info"></div>
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123">
<script>
getImageSize($('#image'), function(width, height) {
$('#info').text(width + ',' + height);
});
function getImageSize(img, callback) {
var $img = $(img);
var wait = setInterval(function() {
var w = $img[0].naturalWidth,
h = $img[0].naturalHeight;
if (w && h) {
clearInterval(wait);
callback.apply(this, [w, h]);
}
}, 30);
}
</script>
One way is to use the HEAD request, which asks for HTTP Header of the response only. I know in HEAD responses, the size of the body is included. But I don't know if there anything available for size of images.