Error image given has not completed loading

Error: Error: Image given has not completed loading at /home/f-user/passport-facebook/examples/login/app.js:315:17 at fs.readFile (fs.js:176:14) at Object.oncomplete (fs.js:297:15) Code: var canvas...

Me too.
Mac OSX 10.9.4

      // add grid:
      var img = new Image
      var request = require('request').defaults({ encoding: null });
      request.get(glance.media.gridC.url, function (error, response, body)
      {
          if (!error && response.statusCode == 200)
          {
              //data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
              //console.log(data);
              c(fn,'request complete downloading ',glance.media.gridC.url)
              // img.dataMode = Image.MODE_IMAGE; // Only image data tracked
              // img.dataMode = Image.MODE_MIME; // Only mime data tracked
              img.dataMode = Image.MODE_MIME | Image.MODE_IMAGE; // Both are tracked
              img.src = new Buffer(body)
              img.xpos = startOffset.x
              img.ypos = startOffset.y
              img.scaleX = 1
              img.scaleY = 1
              //img.onload = function ()
              //{
                c(5)

                console.log('grid start location:',glance.grid.start.offset);
                // top left corner:
                //ctx.drawImage(img,0,0);
                // start:
                ctx.drawImage(img,-glance.grid.start.offset.x,-glance.grid.start.offset.y);

self.options.done() // called when job is completed

                // add function to execute every animation engine cycle
                //TweenMax.ticker.addEventListener("tick", loop);
                //TweenMax.to(img, 1.5, {xpos:100,ypos:100,repeat:-1,yoyo:true});
                //TweenMax.to(img, 15, {xpos:-500,ypos:-100,repeat:-1,yoyo:true, ease:Power2.easeInOut});
                //animate from 0 to whatever the scaleX/scaleY is now
                //TweenMax.to(img, 5, {scaleX:glance.grid.start.scale, scaleY:glance.grid.start.scale});
              //}
          }
      });

Error: Image given has not completed loading

Содержание

  1. Chris Tierney
  2. ColdFusion Web Application Server Stack Blog
  3. img Element error Event
  4. Image Binding Error Handling in Vue.js
  5. 😕 without @error
  6. 😍 with @error
  7. 💯 Conclusion
  8. 👋 Say Hi
  9. Error code from img
  10. Error parsing image file exception on HTTP errors with cURL #253
  11. Comments
  12. Image given has not completed loading #289
  13. Comments

Chris Tierney

ColdFusion Web Application Server Stack Blog

img Element error Event

If you develop and push to production, you most likely have experienced broken images on your dev instance. You may have also run into broken images on production due to user/admin error, etc. Wouldn’t it be nice if you could display a default placeholder image without having to take a hit on your file system, checking to see if it exists, before your load each image?

Thanks to Ryan Stille’s recent blog post, I have been made aware of a (not so great) solution. Apparently the img tag, along with others such as object, script and style have error events. We can listen for the error event and load a placeholder image in place of the default browser error image.

The catch is the event handler must be attached before the browser fires the error event. Also, the error event may not be correctly fired when the page is served locally. The error event relies on HTTP status codes and will generally not be triggered if the URL uses the “file:” protocol.

In simpler terms, the only solution I’ve found is to either place the event handler inline with the img tag, assign the img src via JavaScript or recursively search each image’s complete state or naturalWidth once the window is done loading. I’ve tried using “$().on()” and “$(“img”).error()” both after the document loads and inline before the element is loaded. However neither solution works, which doesn’t make much sense to me.

I am including multiple examples because this is not a one-solution-fits-all scenario.

The first working example displays a placeholder image using the inline method if the error event is thrown. Notice the onerror handler is reset when it’s run so you don’t run into an infinite loop if your placeholder image also fails.

The second working example, also using the inline method, will call a script that will report the broken image and load the placeholder. The script returns an image with the proper image MIME type.

The third working example uses JavaScript to load the image and displays a placeholder if that image fails to load.

The final working example recursively searches through each image after the window loads. If it finds the state incomplete or the natural width of the image is 0, then it loads the placeholder image.

Источник

Image Binding Error Handling in Vue.js

🐛 We all know that broken images don’t look good and they give a very bad user experience.

👉 I was working on a project and instead of showing an alt text if the image is broken, I wanted to show some other alternate image. For this, first, I needed to check if the image is broken then show the alternate image.

👀 I looked for solutions and some people were doing it by styling broken images which is also good but this was not the solution I was looking for.

🙌 I came to know about @error event on images and this proved really helpful.

👨‍💻 Let’s explore this with a code example:

😕 without @error

If we don’t use @error and just provide the alt text, it looks ugly.

Exit fullscreen mode

😍 with @error

By using the @error event on images, we can show the alternate image if the original image is broken or not loaded for any reason. @error will only call the provided method if there is any error in loading the original image.

Exit fullscreen mode

imgUrlAlt is the method that sets the image’s src to alternate image.

Exit fullscreen mode

💯 Conclusion

I really liked achieving the same thing in 3-5 lines with @error and avoiding writing extra 10-15 lines of CSS.

👋 Say Hi

I am quite active on Twitter you can follow me there or visit my Blog to know more about me.

Источник

Error code from img

$_FILES and $_POST will return empty

Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple «maximum file sizes».

The two widely known limits are the php.ini settings «post_max_size» and «upload_max_size», which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names «max_file_size» (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made — see bug #40387 — http://bugs.php.net/bug.php?id=40387) vague references to «allows browsers to check the file size before uploading». This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big — this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).

When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp

If not the $_FILES show you an error #6 «Missing a temporary folder

I have expanded @adam at gotlinux dot us’s example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.

class Some <
/**
* Upload error codes
* @var array
*/
private static $upload_errors = [];

public function __construct () <
// Init upload errors
self :: $upload_errors = [
UPLOAD_ERR_OK => _ ( ‘There is no error, the file uploaded with success.’ ),
UPLOAD_ERR_INI_SIZE => _ ( ‘The uploaded file exceeds the upload_max_filesize directive in php.ini.’ ),
UPLOAD_ERR_FORM_SIZE => _ ( ‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.’ ),
UPLOAD_ERR_PARTIAL => _ ( ‘The uploaded file was only partially uploaded.’ ),
UPLOAD_ERR_NO_FILE => _ ( ‘No file was uploaded.’ ),
UPLOAD_ERR_NO_TMP_DIR => _ ( ‘Missing a temporary folder.’ ),
UPLOAD_ERR_CANT_WRITE => _ ( ‘Cannot write to target directory. Please fix CHMOD.’ ),
UPLOAD_ERR_EXTENSION => _ ( ‘A PHP extension stopped the file upload.’ ),
];
>
>
?>

One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space. Even though «no error» is 0, which typically evaluates to «false» in an if statement, it will always evaluate to true in this context.

So, instead of this:
——
if( $_FILES [ ‘userfile’ ][ ‘error’ ]) <
// handle the error
> else <
// process
>
?>
——
You have to do this:
——
if( $_FILES [ ‘userfile’ ][ ‘error’ ]== 0 ) <
// process
> else <
// handle the error
>
?>
——
Also, ctype_digit fails, but is_int works. If you’re wondering. no, it doesn’t make any sense.

You ask the question: Why make stuff complicated when you can make it easy? I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement. In a loop, that would be deadly. try this instead:

——
= array(
1 => ‘The uploaded file exceeds the upload_max_filesize directive in php.ini.’ ,
‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.’ ,
‘The uploaded file was only partially uploaded.’ ,
‘No file was uploaded.’ ,
6 => ‘Missing a temporary folder.’ ,
‘Failed to write file to disk.’ ,
‘A PHP extension stopped the file upload.’
);

// Outside a loop.
if( $_FILES [ ‘userfile’ ][ ‘error’ ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ ‘userfile’ ][ ‘error’ ]];
// do whatever with the error message
>

// In a loop.
for( $x = 0 , $y = count ( $_FILES [ ‘userfile’ ][ ‘error’ ]); $x $y ;++ $x ) <
if( $_FILES [ ‘userfile’ ][ ‘error’ ][ $x ]== 0 ) <
// process
> else <
$error_message = $error_types [ $_FILES [ ‘userfile’ ][ ‘error’ ][ $x ]];
// Do whatever with the error message
>
>

// When you’re done. if you aren’t doing all of this in a function that’s about to end / complete all the processing and want to reclaim the memory
unset( $error_types );
?>

Источник

Error parsing image file exception on HTTP errors with cURL #253

I have an issue that is driving me insane, hopefully someone can shed some light. I have pages in a WordPress environment that generate PDFs. One is in a directory located at the root of the WP filesystem and is called directly (no WP URL rewrite). The other is served from WP and the code for PDF generation is located in functions.php for the theme.

The page located in the directory at the WP root works fine. The PDF generated from functions.php, which is nearly identical to the other page, constantly throws this error:

The html that’s being rendered is identical. I’m using WriteFixedPosHTML to add an image to the document. The page that works defines this image as:

The code in functions.php, which doesn’t work, defines the image as:

I have to define it this way otherwise I get the error regardless. I have tried the following:

  • Setting src local to function.php: src=»img/logo_new.gif», results in
  • Setting src to be src=»https://github.com/mpdf/mpdf/rw/img/log_new.gif», results in

note the path hasn’t changed

So, for the life of me I don’t understand why

  1. One page works with relative pathing and the other doesn’t (. )
  2. The page that doesn’t work doesn’t seem to recognize the image as being valid. I can browse to http://dev.xxxx.com/wp-content/themes/rw/img/logo_new.gif just fine.

The php code used to generate pdfs from both pages is identical

I’m using mPDF v6 and PHP v5.4.45

The text was updated successfully, but these errors were encountered:

Hmmm, does this issue looks like yours? #13 (just converting the url to base64 helped in this issue. ) Question: why.

There is one other place where I could find the error message in the code, i.e. in utils/image_details.php

(The getImage() function is from about line 9347 to 9880 of mpdf.php )

@bcarroll2k3 Did you ever solve this? I have the exact same issue, also with WP thrown into the mix. Strange thing is that my code works on one particular shared hosting (and on my XAMPP on my local machine), but not on another, so I suspect some difference in GDlib version, maybe? Best regards.

@cjsinnbeck in my case, I need to allow allow_url_fopen in php settings, because my image was not hosted on the same server.

I was also getting the «Error parsing image file — image type not recognised, and not supported by GD imagecreate» error. In my case, it was caused by having an .htaccess password in place.

I had a similar issue and I fixed it by adding streamwrappers to the $options of the MpdfMpdf() constructor:
‘whitelistStreamWrappers’ => stream_get_wrappers(),

I have the same error message using mpdf8.0.x but the error seems to be a red-herring and it seems that the curl_exec is quietly failing in RemoteContentFetcher.php.

As a temporary local edit, I’ve added the following code after the $data = curl_exec($ch) line.

.. this exposes that the underlying problem is a 404 Not Found. I’ve not worked out why the curl_error($ch) doesn’t pick up the error (setting CURLOPT_FAILONERROR to true doesn’t make it happen either).

The mpdf problem seems to be around the fact that the curl isn’t being allowed to read the image URL and I’ve not been able to work this out (putting in a simple curl test bed seems to result no solution), but as a mPDF work-around I have switched from using the img URL to the img filename, i.e. src=’/var/www/vhosts/. ‘> (as the file I’m PDF’ing is on my local host anyway).

it would be good if the curl_exec error checking could be added in the Git code — I’ll leave that to the code managers.

Источник

Image given has not completed loading #289

Error:
Error: Image given has not completed loading
at /home/f-user/passport-facebook/examples/login/app.js:315:17
at fs.readFile (fs.js:176:14)
at Object.oncomplete (fs.js:297:15)

var canvas = new Canvas(650, 650)
, ctx = canvas.getContext(‘2d’);
fs.readFile(__dirname + ‘/public/resimg/1.jpg’, function(err, squid) <
if (err) throw err;
img = new Canvas.Image;
img.src = squid;
img.onload = function() <
console.log(«ian here in onload»);
ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
>
>);

I have seen similar issues here, they mentioned to use «img.onload» in case we get this error «Image given has not completed loading»

But img.onload is not getting fired in my case.
May i know how to fix for this issue.
Thanks

The text was updated successfully, but these errors were encountered:

@visionmedia Can you please look after this issue.
Thanks

This issue affects me too. The code from examples/pdf-images.js can be used to reproduce it.

Stracing the application show that the image is really not loaded (only 4096 bytes are read before the error message is printed). I will try to investigate it as well.

Well, installing libjpeg62-dev on debian make it work 🙂 The Image::loadSurface() method only returns a CAIRO_STATUS_READ_ERROR , without much more informations, if the format is not supported.

still got the same message 🙁

/Users/jiguang/www/node/api.js:24
ctx.drawImage(img, 0, 0);
^
Error: Image given has not completed loading
at IncomingMessage. (/Users/jiguang/www/node/api.js:24:13)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

I was having this problem. I installed libjpeg (used ‘brew install libjpeg’ on osx). And it worked!

I had the same issue for Ubuntu 12.04 LTS. Solution was to remove canvas, uninstall libjpeg-dev, libjpeg62-dev; install libjpeg8-dev; install canvas again.

I’m experiencing this issue on smartOS as well. We don’t have access to as many jpeg libraries as well.. This is a bummer

Experiencing this too on OSX. Tried brew install libjpeg. No go for me. node-canvas V1.1.6

Me too .
Mac OS X 10.9.

Me too.
Mac OSX 10.9.4

Error: Image given has not completed loading

I’m on OS-X as well and I followed the extra steps in the Windows installation.
https://github.com/Automattic/node-canvas/wiki/Installation%3A-Windows
It worked after using node-gyp to build the native module

I tried @dzeikei trick on OS-X 10.9.5 and no bueno still same results

I’ve been able to dodge this issue using readFileSync() method instead of readFile()/img.onload

For everybody on this ticket and for all those who will arrive in the future, please note that this error message MAY occur because you are attempting to load an image type that canvas does not support — probably due to a limited cairo build. You can verify this by trying to load a PNG instead which is typically supported. It is not clear why loading an unsupported image type results in this error message.

Having the same issue to load jpg images. Tried installing libjpeg through brew still no luck. Works for PNG images and not for JPG images

I was having this same problem, and the solution given by yhostc discussed in this issue ended up solving it:

@redspider How can we add JPEG support for node-canvas?

@tomerb15 node-canvas doesn’t care about image types, if I recall correctly it is cairo that cares (cairo is a dependency). You have to make sure your cairo build has JPEG enabled. I can’t help you with that though.

I was having the issue every time when I tried to render the PNG image below onto the canvas.

I noticed that the rendering worked fine for other PNG images. So I used a hex editor (http://entropymine.com/jason/tweakpng/) to see what is different about the file.

The obvious difference was the header:

I removed the ancillary tEXt chunk, saved the file and re-rendered without any errors.

This fixed the issue for me. There might me other chunks that confuse canvas when rendering. It would be really nice to have some basic data cleansing there to save us fiddling around with binary formats.

I’m having the same problem even when I use readFileSync.

My OS is Windows 10, and I’ve installed node-canvas as guided, and somehow it always fails with
drawImage function.

@redspider the reason of getting this error message is that when we try to use(draw) the image, it’s actually not completed loaded yet. If you add a handler on img.onerror you will see this error instead: «Error: error while reading from input stream». And we should stop processing right there.

I was getting this as well which was weird because I was sure the image was loaded before setting the data. But as mentioned above setting an onerror handler gave me a (weird) error.

It said «Out of memory» but it clearly wasn’t. The issue ended up being a sRGB color profile that libpng didn’t like. Stripping that fixed my issue. (in case anyone is ending up here from a google search like I did)

In my case it was IEC619966-2.1 that was the problem. Other pngs with other profiles worked fine.

I’m running into this on two Windows 7 machines and a Windows 10 machine. The image files are normal JPGs, and the same code with the same images works great on macOS.

As others have found, it looks like when following the install instructions for Windows (installing libjpgturbo), Cairo gets built without JPG support. The same code works fine if you work with PNGs.

So. maybe it’s just a documentation issue?

There are a few different issues in this thread.

@endquote and @jshin49 JPEG support for Windows is PR #841 and isn’t merged yet (but is functional if you want to use his fork). I’m not sure exactly what you’re doing without more context, but that is likely what you’re hitting. (And you’re right, the install wiki has been updated already, even though code hasn’t been merged yet!)

@yeldarby That’s interesting and I think merits a new issue. The only other issue I see for color profiles is #725, which isn’t what you’ve described.

A lot of the other reports I think are from building node-canvas without libjpeg support (at least three different posters). For debian/ubuntu this means having libjpeg-dev (or a variant), for MacOS see the wiki instructions https://github.com/Automattic/node-canvas/wiki/Installation:-Mac-OS-X#having-trouble-with-gif-or-jpegs. For windows, as above, that means using the fork in #841 or waiting for that to be merged.

Finally, a lot of this is better described in #486 («not completed loading» is misleading) — this error message occurs in a variety of situations unrelated to image loading: in addition to having a build without JPEG support, it apparently happens specifically for some color profiles (#289 (comment)) and unhandled PNG header chunks (#289 (comment)).

Источник

I’m trying to use node-canvas to manipulate an image stored on a remote server. I started with the image-src example and modified it, but I can’t get it to work. Here’s my code:

var fs = require('fs'),
    http = require('http'),
url = require('url'),
canvas = require('./node-canvas/lib/canvas');

var outCanvas = new canvas(1000, 750);
var ctx = outCanvas.getContext('2d');

http.get(
    {
        host: 'farm8.staticflickr.com',
        port: 80,
        path: '/7108/7038906747_69a526f070_z.jpg'
    },
    function(res) {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function () {
            img = new canvas.Image;
            img.src = data;
            ctx.drawImage(img, 0, 0, img.width, img.height);

            var out = fs.createWriteStream(__dirname + '/my-out.png')
                , stream = outCanvas.createPNGStream();

            stream.on('data', function(chunk){
                out.write(chunk);
            });
        });
    }
);

…and here’s the error I’m getting:

/Users/daf/Documents/lolstagram/lolstagram-c.js:23
    ctx.drawImage(img, 0, 0, img.width, img.height);
       ^
Error: Image given has not completed loading
    at IncomingMessage.<anonymous> (/Users/daf/Documents/lolstagram/lolstagram-c.js:23:8)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)

Any idea what the problem might be? Thanks.


You’re treating the data in the response as a String when you need to keep it as binary data in a Buffer. Node-canvas is expecting binary data to be passed into img.src.

This should work inside your http response handler:

var data = new Buffer(parseInt(res.headers['content-length'],10));
var pos = 0;
res.on('data', function(chunk) {
  chunk.copy(data, pos);
  pos += chunk.length;
});
res.on('end', function () {
  img = new canvas.Image;
  img.src = data;
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var out = fs.createWriteStream(__dirname + '/my-out.png')
    , stream = outCanvas.createPNGStream();

  stream.on('data', function(chunk){
    out.write(chunk);
  });
});

I’m trying to use node-canvas to manipulate an image stored on a remote server. I started with the image-src example and modified it, but I can’t get it to work. Here’s my code:

var fs = require('fs'),
    http = require('http'),
url = require('url'),
canvas = require('./node-canvas/lib/canvas');

var outCanvas = new canvas(1000, 750);
var ctx = outCanvas.getContext('2d');

http.get(
    {
        host: 'farm8.staticflickr.com',
        port: 80,
        path: '/7108/7038906747_69a526f070_z.jpg'
    },
    function(res) {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function () {
            img = new canvas.Image;
            img.src = data;
            ctx.drawImage(img, 0, 0, img.width, img.height);

            var out = fs.createWriteStream(__dirname + '/my-out.png')
                , stream = outCanvas.createPNGStream();

            stream.on('data', function(chunk){
                out.write(chunk);
            });
        });
    }
);

…and here’s the error I’m getting:

/Users/daf/Documents/lolstagram/lolstagram-c.js:23
    ctx.drawImage(img, 0, 0, img.width, img.height);
       ^
Error: Image given has not completed loading
    at IncomingMessage.<anonymous> (/Users/daf/Documents/lolstagram/lolstagram-c.js:23:8)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)

Any idea what the problem might be? Thanks.

Skip to content



Open


Issue created May 13, 2019 by Corey Schram@cschramOwner

Image given has not completed loading

Server-side canvas rendering sometimes fails with the following error:

UnhandledPromiseRejectionWarning: Error: Image given has not completed loading
    at NodeBrushTool.getImage (/opt/drawgaiden/dist/lib/canvas.js:40:25)
    at NodeBrushTool.<anonymous> (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:102:51)
    at step (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:45:23)
    at Object.next (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:26:53)
    at /opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:20:71
    at new Promise (<anonymous>)
    at __awaiter (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:16:12)
    at NodeBrushTool.BrushTool.drawLine (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:96:16)
    at NodeBrushTool.<anonymous> (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:172:34)
    at step (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:45:23)
    at Object.next (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:26:53)
    at /opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:20:71
    at new Promise (<anonymous>)
    at __awaiter (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:16:12)
    at NodeBrushTool.BrushTool.draw (/opt/drawgaiden/node_modules/@drawgaiden/easel/lib/tools/brush.js:146:16)
    at Object.<anonymous> (/opt/drawgaiden/dist/lib/canvas.js:104:42)

Brush images are loaded asynchronously but the canvas render does not wait for it to be finished, causing this error. Use node-canvas’ loadImage to fix this.

Я пытаюсь использовать node-canvas для управления изображением, хранящимся на удаленном сервере. Я начал с примера image-src и изменил его, но не могу заставить его работать. Вот мой код:

var fs = require('fs'),
    http = require('http'),
url = require('url'),
canvas = require('./node-canvas/lib/canvas');

var outCanvas = new canvas(1000, 750);
var ctx = outCanvas.getContext('2d');

http.get(
    {
        host: 'farm8.staticflickr.com',
        port: 80,
        path: '/7108/7038906747_69a526f070_z.jpg'
    },
    function(res) {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function () {
            img = new canvas.Image;
            img.src = data;
            ctx.drawImage(img, 0, 0, img.width, img.height);

            var out = fs.createWriteStream(__dirname + '/my-out.png')
                , stream = outCanvas.createPNGStream();

            stream.on('data', function(chunk){
                out.write(chunk);
            });
        });
    }
);

… и вот ошибка, которую я получаю:

/Users/daf/Documents/lolstagram/lolstagram-c.js:23
    ctx.drawImage(img, 0, 0, img.width, img.height);
       ^
Error: Image given has not completed loading
    at IncomingMessage.<anonymous> (/Users/daf/Documents/lolstagram/lolstagram-c.js:23:8)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)

Есть идеи, в чем может быть проблема? Спасибо.

Я пытаюсь использовать Resemble.js в узле. У меня было немного проблем с установкой canvas/cairo (что-то связанное с сочетанием OS X Mavericks/XQuarts и Homebrew), но в итоге получилось.

Довольно далеко, но я ударил стену этим.

function ImageSimilarityChecker(){
    var resemble = require("resemble").resemble;
    var fs = require("fs");
    var util = require("util");

    this.admitImage = function(imagePath)
    {

        fs.readFile(imagePath, function (err, fileData) 
        {
            if (err) throw err;
            else 
            {
                var api = resemble(fileData).onComplete(function(data){
                    console.log(imagePath);
                    console.log(util.inspect(data));
                });
            }
        });

    }
}

new ImageSimilarityChecker().admitImage("./public/images/test.jpg");

Результаты этой ошибки:

/Users/pcoghill/Projects/imgManip/auth/Servers/Farm/node_modules/resemble/lib/server.js:38
      context.drawImage(hiddenImage, 0, 0, width, height);
              ^
Error: Image given has not completed loading
    at load (/Users/pcoghill/Projects/imgManip/auth/Servers/Farm/node_modules/resemble/lib/server.js:38:15)
    at module.exports.loadImageData (/Users/pcoghill/Projects/imgManip/auth/Servers/Farm/node_modules/resemble/lib/server.js:11:7)
    at Object.onComplete (/Users/pcoghill/Projects/imgManip/auth/Servers/Farm/node_modules/resemble/resemble.js:508:5)
    at /Users/pcoghill/Projects/imgManip/auth/Servers/Farm/resembleFile.js:14:39
    at fs.js:271:14
    at Object.oncomplete (fs.js:107:15)

Я новичок в узле, поэтому не вижу, как изображение не загружено. Это локальный файл, и я обрабатываю его при чтении завершенного обратного вызова (или, как я думаю).

Небольшое копание заставляет меня думать, что это проблема в холсте при чтении jpg файлов, но я изо всех сил пытаюсь понять детали. Я нашел этот вопрос, который выглядит очень похожим, но я не вижу, как преобразовать его в мою ситуацию.

Может кто-нибудь объяснить, как я могу это исправить и что я делаю неправильно?

I keep getting the following error as soon as I add a layer to a map and try to save it as an image.


Complete log :

/home/gregory/code/tsm-aveyron/node_modules/jsdom/lib/jsdom/living/nodes/HTMLCanvasElement-impl.js:128
    return prev.apply(ctx, arguments);
                ^

Error: Image given has not completed loading
    at CanvasRenderingContext2D.ctx.(anonymous function) [as drawImage] (/home/gregory/code/tsm-aveyron/node_modules/jsdom/lib/jsdom/living/nodes/HTMLCanvasElement-impl.js:128:17)
    at drawTile (/home/gregory/code/tsm-aveyron/node_modules/leaflet-image/index.js:174:17)
    at Array.forEach (<anonymous>)
    at Queue.tileQueueFinish [as _call] (/home/gregory/code/tsm-aveyron/node_modules/leaflet-image/index.js:169:18)
    at maybeNotify (/home/gregory/code/tsm-aveyron/node_modules/d3-queue/build/d3-queue.js:109:34)
    at /home/gregory/code/tsm-aveyron/node_modules/d3-queue/build/d3-queue.js:85:14

Example :

For example, the following code works fine :

var L = require('leaflet-headless');

const map = L.map(document.createElement('div')).setView([52, 4], 10);

L.marker([52, 4]).addTo(map);
L.polyline([[52, 4], [54, 4], [54, 6], [52, 6], [52, 4]]).addTo(map);

map.saveImage('test.png', function (filename) {
    console.log('Saved map image to ' + filename);
}); 

But Error: Image given has not completed loading will be thrown for the following code :

var L = require('leaflet-headless');

const map = L.map(document.createElement('div')).setView([52, 4], 10);

L.marker([52, 4]).addTo(map);
L.polyline([[52, 4], [54, 4], [54, 6], [52, 6], [52, 4]]).addTo(map);

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map); // /! Trying to add a layer makes the script crashes during the image export /!

map.saveImage('test.png', function (filename) {
    console.log('Saved map image to ' + filename);
});

Additional infos :

I tried to install libjpeg62-dev, it did not help.


Any idea? Thanks 😄

Понравилась статья? Поделить с друзьями:
  • Error illegalattributevalue при печати
  • Error illegal use of an object as a name
  • Error illegal start of type java
  • Error illegal start of expression java
  • Error illegal operator sequence