I need to let user load one image from her local file system into the browser for some editing.
I don't wanna use flash or others. Only HTML and JavaScript.
So what I do is to let user upload the image to the server and the server returns the contents of the file (using php file_get_contents).
Now I have the contents of the image file as a string in JavaScript. I expected to assign this string to the src of an image element and it shows up. But when I assign it to src, nothing happens.
What's wrong? What's the solution?
src means an URL.
Either set that to an URL on the server, or use a Base64 encoded image:
PHP:
$imagedata = file_get_contents($file);
$encoded = base64_encode($imagedata);
echo $encoded;
JavaScript:
var imageElem = document.getElementById('image');
var filetype = 'png'; // Set file type here
imageElem.src = 'data:image/' + filetype + ';base64,' + image;
Related
I have a problem when trying to create my Telegram's Instant View template, with this error:
Resource fetch failed: https://gdude.de/blog/assets/images/Kaggle-Lyft/task.webp
Resource fetch failed: https://gdude.de/blog/assets/images/telegram.ico
The URLs are valid, I have checked.
These are the only two images that fail. Does IV support *.webp and *.ico images?
According to their manual, Instant View is only actually supporting gif, jpg and png.
with the attribute src and the optional attribute href to make the image clickable. Allowed formats: GIF, JPG, PNG (GIF would be converted into Video type by IV)
I had a similar problem and solved it in the following way.
Note: You need a hosting server to store a PHP script, a free one worked for me (000Webhost).
The diagram below represents the general idea
Instant View code
Note: I'm a beginner at Instant View and XPath, so for now I'm just writing code that works.
# Find unsupported images
$imgs: //img[ends-with(#src, ".webp")]
$imgs+: //img[ends-with(#src, ".ico")]
# Temporary element to create the URLs and make calls to the conversion service
#html_to_dom: "<a>"
$tmp_tag
# For each unsupported image
#map($imgs){
$img: $#
# Build de URL to request the image conversion service
#set_attr(href, "https://my-free-subdom.000webhostapp.com/imgconverter.php?url=", $img/#src): $tmp_tag/a
# Make the request
#load: $tmp_tag/a/#href
# Change the src of the unsupported image to that of the converted image created by the conversion service
#set_attr(src, $#//img/#src): $img
}
#remove: $tmp_tag
PHP script to convert the image
To handle the ICO files I used the IcoFileLoader library, I found it thanks to this question PHP GD .ico handling. I just took the PHP files from the src directory and put them directly on my hosting, so I had to use a simple Autoloader.
// The URL of the image to convert
// If the url of the image is relative, you have
// to build it here, example $url = 'https://gdude.de'.$_GET['url'];
$url = $_GET['url'];
// File name
$file_name = basename($url);
// Directory where the image will be saved
$dir = './';
// File location
$save_file_loc = $dir . $file_name;
// Open file
$fp = fopen($save_file_loc, 'wb');
// Download the image using CURL
$ch = curl_init($url);
// Set options for a cURL transfer
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
// Close file
fclose($fp);
// Load the image
// ICO images need special handling
if(str_ends_with($file_name, '.ico'))
{
require_once('Autoloader.php');
$loader = new IcoFileService;
// You must define the size, I did the tests with a 16X16 favicon.
$im = $loader->extractIcon($file_name, 16, 16);
}
else if(str_ends_with($file_name, '.webp'))
{
$im = imagecreatefromwebp($file_name);
}
// Check if the image was loaded
if(!isset($im))
{
die('Unable to load image!');
}
// Convert it to a png file
imagepng($im, $file_name.'.png');
imagedestroy($im);
// Delte the original image
unlink($file_name);
// "Return" the image in an HTML tag so that Instant View can handle it
echo '<img src="https://my-free-subdom.000webhostapp.com/' . $file_name . '.png">';
Feel free to improve the above code, perhaps add some security, delete old images, use other libraries or PHP functions, accept multiple images in the same request, etc.
I found imageoptim to be helpful for free conversion of (in my case) svg images. Just prepend this url to the svg url and they'll start to load. I chose a resolution of 2560 as it's the max resolution that IV 2.1 supports.
#set_attr(src, "https://img.gs/<your-username>/2560,fit,format=png,quality=high/", ./#src): $body//img[contains(#src, ".svg")]
#set_attr(srcset, "https://img.gs/<your-username>/2560,fit,format=png,quality=high/", ./#srcset): $body//img[contains(#srcset, ".svg")]
Here is the problem I have:
My users can set their profile image either from Facebook (which is a jpeg or gif) or from local device (which could be png or jpg or others).
I get the image from Facebook by using:
// Get the name, email and picture
final graphResponse = await http.get(
'https://graph.facebook.com/v4.0/me?fields=name,email,picture.width(300).height(300)&access_token=$token');
// Decode JSON
final profile = jsonDecode(graphResponse.body);
final String stringData = profile['picture']['data'];
final bytes = Uint8List.fromList(stringData.codeUnits);
And getting image from local device by:
final imagePicker = ImagePicker();
// Call image picker
final pickedFile = await imagePicker.getImage(
source: ImageSource.gallery,
maxWidth: MAX_WIDTH_PROFILE_IMAGE,
);
final imageBytes = await pickedFile.readAsBytes();
Then all I got here are in bytes (Uint8List), how do I save it according to its original extension?
Then later on how do I read them again without checking its extension?
Such as with:
// Setting the filename
// Could be jpg or png or bmp or gif.
// How to determine the extension?
final filename = 'myProfileImage';
// Getting App's local directory
final Directory localRootDirectory =
await getApplicationDocumentsDirectory();
final String filePath = p.join(localRootDirectory.path, path, filename);
final file = File(filePath);
You see, when reading the file we need to specify the full filename. But how to determine the extension then ?
You can avoid dealing with extensions completely by simply not setting an extension in the filename. Extensions only exist to indicate what is likely contained within a file for an OS, but they are not necessary and aren't needed in your case especially since you know that you have some kind of image data in that file and you application is probably the only thing ever using that file.
However, if you really do want to use extensions in the filename, you can use the image package. This provides a Decoder abstract class with multiple implementers for a variety of image encoding methods. To determine which method was used for your file you could check with the isValidFile of each possible decoder type that you need and write an extension accordingly.
Example:
PngDecoder png = PngDecoder();
if(png.isValidFile(data //Uint8List inputted here)) {
print("This file is a PNG");
}
I'm trying to download a PNG image in Apps Script, convert it to JPEG, and generate a data URI for this new JPEG.
function test() {
var blob = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob();
var jpeg = blob.getAs("image/jpeg");
var uri = 'data:image/jpeg;base64,' + Utilities.base64Encode(jpeg.getBytes());
Logger.log(uri);
}
When I run this, I get:
The image you are trying to use is invalid or corrupt.
Even something like:
function test() {
var bytes = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob().getBytes();
var jpeg = Utilities.newBlob(bytes, MimeType.PNG).getAs(MimeType.JPEG);
DriveApp.createFile(jpeg);
}
doesn't work.
Your code is correct. This may be a bug, but it's specific to the file you are using, so may as well be a bug in the file (i.e., the file could indeed be corrupted somehow). Or maybe it uses some features of PNG format that Google doesn't handle. Replacing the URL by another one, e.g.,
var blob = UrlFetchApp.fetch('https://cdn.sstatic.net/Sites/mathematica/img/logo#2.png').getBlob();
both functions work as expected.
I have a phantomjs script that is stepping through the pages of my site.
For each page, I use page = new WebPage() and then page.close() after finishing with the page. (This is a simplified description of the process, and I'm using PhantomJS version 1.9.7.)
While on each page, I use page.renderBase64('PNG') one or more times, and add the results to an array.
When I'm all done, I build a new page and cycle through the array of images, adding each to the page using <img src="data:image/png;base64,.......image.data.......">.
When done, I use page.render(...) to make a PDF file.
This is all working great... except that the images stop appearing in the PDF after about the 20th image - the rest just show as 4x4 pixel black dots
For troubleshooting this...
I've changed the render to output a PNG file, and have the same
problem after the 19th or 20th image.
I've outputted the raw HTML. I
can open that in Chrome, and all the images are visible.
Any ideas why the rendering would be failing?
Solved the issue. Turns out that PhantomJS was still preparing the images when the render was executed. Moving the render into the onLoadFinished handler, as illustrated below, solved the issue. Before, the page.render was being called immediately after the page.content = assignment.
For those interested in doing something similar, here's the gist of the process we are doing:
var htmlForAllPages = [];
then, as we load each page in PhantomJS:
var img = page.renderBase64('PNG');
...
htmlForAllPages.push('<img src="data:image/png;base64,' + img + '">');
...
When done, the final PDF is created... We have a template file ready, with all the required HTML and CSS etc. and simply insert our generated HTML into it:
var fs = require('fs');
var template = fs.read('DocumentationTemplate.html');
var finalHtml = template.replace('INSERTBODYHERE', htmlForAllPages.join('\n'));
var pdfPage = new WebPage();
pdfPage.onLoadFinished = function() {
pdfPage.render('Final.pdf');
pdfPage.close();
};
pdfPage.content = finalHtml;
I have a folder with images: IMG1.jpg, IMG2.jpg, IMG3.jpg, IMG4.jpg.
I do:
BufferedImage _img = null;
_img = ImageIO.read(new File(PATH_TO_IMAGE + "\\IMG"+Id+".jpg")); //where id is the number.
Then the rest...
BufferedDynamicImageResource bufferedDynamicImage = new BufferedDynamicImageResource();
bufferedDynamicImage.setImage(_img);
Image ci = new Image("myImg", bufferedDynamicImage);
add(ci);
And what I get in the end is that although Wicket knows the exact path to some image (which is shown in Log.file) most time it gets random image from my folder. What could be the reason for this?
Following my comment, what about
Image ci = new Image("myImg");
ci.add(AttributeModifier.replace("src", Model.of(PATH_TO_IMAGE + "\\IMG" + Id + ".jpg")));
add(ci);
This changes the src-attribute of your img-tag according to your desired logic, prevents browser-caching where undesired but enables caching where possible.