Optimal way to define the correct size of a SVG image - svg

When creating a SVG image you have to set width,height and position otherwise it will not be rendered.
How do I read them from the original image?
Using Dart I first load the html image and after it's loaded I get the size and then define the SVG image and use the info I got before. This is a bit cumbersome and I wondered if there is another way.
The dart code looks like this:
ImageElement img = new ImageElement(src:'2.jpg'); //401x600
img.onLoad.listen((e) {
svg.ImageElement image = new svg.ImageElement();
image.setAttribute('x', '0');
image.setAttribute('y', '0');
image.setAttribute('width', img.width.toString());
image.setAttribute('height', img.height.toString());
image.getNamespacedAttributes('http://www.w3.org/1999/xlink')['href'] = '2.jpg';
});

There seems not to be a more convenient method (also not in JavaScript except when you use jQuery or another framework that includes methods for this).
Just create a method yourself and reuse that method for each image you load.

Related

Load images from local directory in Fabric

I am trying to load images from a local folder using fabric.js in node.
There seems to be very little up to date documentation on how to do this.
Most example use fabric.Image.fromURL(imageurl)
As far as I'm aware, this only works for web urls, not local paths.
Correct me if I'm wrong, but I have tried
fabric.Image.fromURL(imgpath, (img) => {
...
}
which throws the error Coul not load img: /image/path/img.jpg
Where
fs.readFile(imagepath, (err, i) => {
...
})
will successfully read the file, i will be a buffer.
What is the correct way to load a local image.
I know there is a fabric.Image.fromObject but I have no idea what type of object it wants.
I am currently loading the image into a 2d canvas object, converting it with canvas.toDataURL() and putting that url into fabric.Image.fromURL() which works but converting the image to a url is very slow due to large images. There must be a way to load the image directly and avoid this problem.
If you are using fabricjs 3+, that uses the new jsdom, you can use the file urls!
fabric.Image.fromURL(file://${__dirname}${filepath});
Check here on the fabricJS codebase how they handle reading files in browser and node for the visual test images
https://github.com/fabricjs/fabric.js/blob/master/test/lib/visualTestLoop.js#L139
try this one:
fabric.Image.fromURL(require("../../assets/mockup/100.png"), (img) => {...}

Getting image from dicom .DCM file in node.js

I would like to generate a thumbnail image from a .dcm file (Dicom) in node.js.
So far I've found a node modules called dicom-parser that extracts the metadata from a dcm file.
My test case :
var dicom = require('dicom-parser');
var fs = require('fs');
var dicomFileAsBuffer = fs.readFileSync('./FullPano.dcm');
var dataSet = dicom.parseDicom(dicomFileAsBuffer);
var pixelData = new Uint8Array(dataSet.byteArray.buffer,
dataSet.elements.x00880200.items[0].dataSet.elements.x7fe00010.dataOffset,
dataSet.elements.x00880200.items[0].dataSet.elements.x7fe00010.length);
fs.writeFileSync('test5.jpg', pixelData); // <----- not working :'(
To help you help me debug, here is the dataSet.elements.x00880200 object :
But the pixelData stored in the tag x00880200 -> x7fe00010 is not in a standard format, either jpeg, jpg, png... The idea here is to get the thumbnail of a dcm image directly from a file, on the fly, server-side in nodejs.
From the dicom doc (see below), the tag 0088,0200 holds the data for the icon, aka thumbnail.
Icon Image Sequence
(0088,0200)
3
This icon image is representative of the Image.
Only a single Item is permitted in this Sequence.
I've come around the cornerstone libs : cornerstone-js and wado-image-loader. But neither are working in a node.js environment (made an issue about that). These libs can generate the "main" image of a dcm, but only once the dcm file is loaded on the cliend-side, in js. My requirement is to do that in nodejs, for the icon/thumbnail.
If you are trying to save the image icon as a JPG, that may be your issue:
Only monochrome and palette color images shall be used. Samples per Pixel (0028,0002) shall have a Value of 1, Photometric Interpretation (0028,0004) shall have a Value of either MONOCHROME 1, MONOCHROME 2 or PALETTE COLOR, Planar Configuration (0028,0006) shall not be present.source
I'm not familiar with node.js, but the data in the Icon Image Sequence may not be appropriate for that call.
Note also that you are getting an optional, small, thumbnail of the image, not the actual image data, which can be found in the Pixel Data attribute (7FE0,0010).
A bit late but, if you are still looking for an answer, you can use dcmjs-imaging (full disclosure, I am the author). The library implements a DICOM image and overlay rendering pipeline, for Node.js and browser.
The library supports uncompressed data but also, optionally, decodes all major transfer syntaxes using a native WebAssembly module.
Given that you have already fetched the the DICOM bytes in an ArrayBuffer, you can use the following Node.js example to render the image in an RGBA pixel ArrayBuffer.
// Import objects
const dcmjsImaging = require('dcmjs-imaging');
const { DicomImage, NativePixelDecoder } = dcmjsImaging;
// Optionally register native decoders WebAssembly.
// If native decoders are not registered, only
// uncompressed syntaxes would be able to be rendered.
await NativePixelDecoder.initializeAsync();
// Create an ArrayBuffer with the contents of the DICOM P10 byte stream.
const image = new DicomImage(arrayBuffer);
// Render image.
const renderingResult = image.render();
// Rendered pixels in an RGBA ArrayBuffer.
const renderedPixels = renderingResult.pixels;
// Rendered width.
const width = renderingResult.width;
// Rendered height.
const height = renderingResult.height;

How to render/generate image according to text/string in nodejs?

How can i generate an image of a string that has:
a size in px
embossed effect of the letters in the image
a font
a color
and other less important stuff that i think i can figure out once i achieve whats above like:
rotation of text
drop shadow
basically the user will send a request on how he wants his image to be.
but when i receive the request how should i make use of nodejs to render a png or a base64 url to send it back to the user. is there any libraries or way to achieve this.
i did some previous research and it doesn't seem like there is a frameworks that helps render text with a font and text style like emboss
You can try node canvas implementation: https://github.com/Automattic/node-canvas
Basically you can "draw" anything you want like if you'd be using browser js canvas, but some things may be different
Update - This will cover updating attributes of an image, not pulling text from image and updating that - you may need an image analysis library for that
Use the sharp library to manipulate the image as desired. https://github.com/lovell/sharp
http://sharp.dimens.io/en/stable/
A simple example that resizes (docs will show how to make the changes you want outside of this):
const request = require('request').defaults({ encoding: null });
request.get(imgUrl, params, function (err, res, body) {
sharp(body)
.resize(params.width, params.height)
.toFormat('jpeg')
.toBuffer()
.then((outputBuffer) => {
// outputBuffer contains JPEG image data no wider than params.width and no higher
// than params.height while maintaining quality of image.
let output = "data:" + res.headers["content-type"] + ";base64," + new Buffer(outputBuffer).toString('base64');
return output;
});
The output here will be the base64 image

Example to show how mobify works

I have been looking at the mobify.js website for a while now, but I fail to understand the benefits of using it. (I am stumped to see why would one replace all the images on the page by GrumpyCat image?).
Could you kindly point me to a clear and lucid example, wherein, I can see that depending on the browser resolution my image size changes.
I have done the following tasks till now:
0. Included mobify.js header information
1. Used the mountains.jpg and forest.jpg image in my hosted website (The page contains only these two images)
2. Request the page from a desktop machine, from a tablet (Samsung Galaxy 10 inch), from an android mobile phone.
3. In all the three cases, I see the same image getting downloaded, the size of the image stays the same in all the cases.
I understand that the magic of size reduction can't happen on the fly, but how do I achieve this?
I realize that the Grumpy Cat example is a bit cheeky, but the same concept applies to solve your problem. Instead of replacing the images with Grumpy Cat images, you could write some logic to replace the images with lower-resolution images (i.e. mountains-320.jpg and forest-320.jpg).
With Mobify.js, you need to write the adaptations in the JavaScript snippet that you added to your site. So, to load smaller images for mobile, you could define the path to the lower resolution image in your original HTML like this:
<img src="mountain.jpg" data-mobile-src="mountain-320.jpg" />
<img src="forest.jpg" data-mobile-src="forest-320.jpg" />
Then, in the JavaScript snippet, you could modify it to grab the image in the data-mobile-src attribute instead like this:
if (capturing) {
// Grab reference to a newly created document
Mobify.Capture.init(function(capture){
// Grab reference to the captured document in progres
var capturedDoc = capture.capturedDoc;
var imgs = capturedDoc.getElementsByTagName("img[data-mobile-src]");
for(var i = 0; i < imgs.length; i++) {
var img = imgs[i];
var ogImage = img.getAttribute("x-src");
var mobileImage = img.getAttribute("data-mobile-src");
img.setAttribute("x-src", mobileImage);
img.setAttribute("old-src", ogImage);
}
// Render source DOM to document
capture.renderCapturedDoc();
});
}
Then, you'll see that the mobile site will download and render mountain-320.jpg or forest-320.jpg, but it will not download mountain.jpg or forest.jpg.
Just out of curiousity, what site are you wanting to use Mobify.js on?

jspdf and addHTML / blurry font

I generate pdf file from a HTML-page via jspdf plugin addHTML.
It works but the rendered text / font is really blurry, the original HTML page is not. Rendered images are fine, only text is the problem (see attached images).
original_image: http://111900.test-my-website.de/stackoverflow/orig.jpg
blurry_image: http://111900.test-my-website.de/stackoverflow/blurry.jpg
I read all google results the last three days - maybe I am the only person in the world I have exact this problem?!?! :/
I added the following scripts in my code:
spdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js
pdf generation code:
pdf.addHTML(document.getElementById("container"),10,15,function() {
var string = pdf.save(filename);
});
Is there a quality option in jspdf I missed?
How can I render the font?
Thanks for reply,
Thomas
I found that when creating a PDF and the text was blurred when using addHtml this was because of the width of the web page. Try using it with the browser not maximised as a test.
My solution was to add some styles to adjust the width before calling addHTML with a width parameter that matches the styles I added. I then remove the additional styles in the function that runs after addHTML.
I had the same problem and I resolved it.
Actually, the main issue here is to specify the 'dpi' to avoid having a blurred image. In addition to that, try to avoid any 'smoothening' features beacuse it may make it worse. I have taken a look around the API and other discussion about it and I came back with the following solution:
1- update your version of html2canvas : many blurring issues have been fixed after the 1.0.0-alpha release.
2- use the following properties :
const context = canvas.getContext('2d');
context.scale(2, 2);
context['dpi'] = 144;
context['imageSmoothingEnabled'] = false;
context['mozImageSmoothingEnabled'] = false;
context['oImageSmoothingEnabled'] = false;
context['webkitImageSmoothingEnabled'] = false;
context['msImageSmoothingEnabled'] = false;

Resources