I have a simple node script to fetch tif image, use sharp to convert the image to jpeg and generate data:image/jpeg;base64 src for browser. The reason is to enable tiff image in browsers that do not support tif/tiff images.
In node this works great.
import sharp from "sharp";
import fetch from "node-fetch";
let link =
"https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif";
// fetch tif image and save it as a buffer
async function fetchTifBuffer(link) {
const tifImg = await fetch(link);
const buffer = await tifImg.buffer();
return buffer;
}
// convert to png image save to buffer and save as base64
async function tifToPngToBase64(link) {
let inputImgBuffer = await fetchTifBuffer(link);
const buff = await sharp(inputImgBuffer).toFormat("jpeg").toBuffer();
let base64data = buff.toString("base64");
let imgsrc = "data:image/jpeg;base64," + base64data.toString("base64");
console.log(imgsrc);
// use in browser <img src="data:image/jpeg;base64,/9j/2wBDAAYEBQYFBAY ...==" alt="image" />
}
tifToPngToBase64(link);
I would like to implement this in SvelteKit. But I have no idea how to get buffer from SvelteKit fetch response. Any ideas?
Ok, so I figured it out by myself. SvelteKit fetch response has an arrayBuffer, so all that is needed is to convert the arraybuffer to the buffer.
This is the relevant SvelteKit endpoint:
// img.js
import sharp from "sharp";
export const get = async () => {
const res = await fetch(
"https://people.math.sc.edu/Burkardt/data/tif/at3_1m4_01.tif"
);
const abuffer = await res.arrayBuffer();
const buffer = Buffer.from(new Uint8Array(abuffer));
const buff = await sharp(buffer).toFormat("jpeg").toBuffer();
let base64data = buff.toString("base64");
let src = `data:image/jpeg;base64,${base64data.toString("base64")}`;
let img = `<img style='display:block; width:100px;height:100px;' id='base64image'
src='${src}' />`;
return {
body: {
img,
},
};
};
and this is the SvelteKit component which uses the endpont:
// img.svelte
<script>
export let img;
</script>
{#html img}
Related
I need help with using sharp, I want my images to resize when uploaded but I can't seem to get this right.
router.post("/", upload.single("image"), async (req, res) => {
const { filename: image } = req.file;
await sharp(req.file.path)
.resize(300, 200)
.jpeg({ quality: 50 })
.toFile(path.resolve(req.file.destination, "resized", image));
fs.unlinkSync(req.file.path);
res.send("sent");
});
As I know you should pass a Buffer to sharp not the path.
Instead of resizing saved image, resize it before save. to implement this, you should use multer.memoryStorage() as storage.
const multer = require('multer');
const sharp = require('sharp');
const storage = multer.memoryStorage();
const filter = (req, file, cb) => {
if (file.mimetype.split("/")[0] === 'image') {
cb(null, true);
} else {
cb(new Error("Only images are allowed!"));
}
};
exports.imageUploader = multer({
storage,
fileFilter: filter
});
app.post('/', imageUploader.single('photo'), async (req, res, next) => {
// req.file includes the buffer
// path: where to store resized photo
const path = `./public/img/${req.file.filename}`;
// toFile() method stores the image on disk
await sharp(req.file.buffer).resize(300, 300).toFile(path);
next();
});
I want to display a pdf as an image on canvas using angular7 and fabric js
i am not able to find any code to try in angular7
Finally i am able to solve this...i have used pdfjsLib and i have imported in my ts file (import * as pdfjsLib from 'pdfjs-dist/build/pdf';)
public src="/assets/myPhotos.pdf";
showPdf(){
pdfjsLib.getDocument(this.src).then(doc =>{
// console.log("this file has "+ doc._pdfInfo.numPages+ "pages");
doc.getPage(1).then(page => {
var myCanvas = <HTMLCanvasElement>document.getElementById("my_canvas");
var context = myCanvas.getContext("2d");
var scale = 1.5;
var viewport = page.getViewport(scale);
myCanvas.width = viewport.width;
myCanvas.height = viewport.height;
page.render({
canvasContext : context,
viewport : viewport
})
})
});
}
I am using the Flutter Plugin Image_picker to choose images so that I want to upload image after selected the image
Future<File> _imageFile;
void _onImageButtonPressed(ImageSource source) async {
setState(() {
_imageFile = ImagePicker.pickImage(source: source);
});
}
I find this code in flutter documentation but its not work
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'nweiz#google.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new MediaType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
Use MultipartRequest class
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Check this answer
This code works properly.
Used MultipartRequest class
void uploadImage() async {
File _image;
File pickedImage = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = pickedImage;
});
// open a byteStream
var stream = new http.ByteStream(DelegatingStream.typed(_image.openRead()));
// get file length
var length = await _image.length();
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "image_file" is a key of the API request
var multipartFile = new http.MultipartFile('image_file', stream, length, filename: basename(_image.path));
// add file to multipart
request.files.add(multipartFile);
// send request to upload image
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
name spaces:
import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
If you want the uploading function to return the server response, you can use toBytes() instead of transform(), in order to wait until data transmission is complete.
Future<String> upload() async {
String responseString = '';
// Pick image
final image = await ImagePicker().getImage(
source: ImageSource.gallery // or ImageSource.camera
imageQuality: 100,
maxWidth: 1000,
);
// Convert to File
final file = File(image.path);
// Set URI
final uri = Uri.parse('URL');
// Set the name of file parameter
final parameter = 'Name';
// Upload
final request = http.MultipartRequest('POST', uri)
..files.add(await http.MultipartFile.fromPath(parameter, file.path));
final response = await request.send();
if (response.statusCode == 200) {
responseString = String.fromCharCodes(await response.stream.toBytes());
}
return responseString;
}
I am trying to improve a gnome-shell-extension by allowing retrieving of remote image (jpg) and set as icon for a certain widget.
Here is what I got so far, but it does not work, due to mismatch of data type:
// allow remote album art url
const GdkPixbuf = imports.gi.GdkPixbuf;
const Soup = imports.gi.Soup;
const _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
function getAlbumArt(url, callback) {
var request = Soup.Message.new('GET', url);
_httpSession.queue_message(request, function(_httpSession, message) {
if (message.status_code !== 200) {
callback(message.status_code, null);
return;
} else {
var albumart = request.response_body_data;
// this line gives error message:
// JS ERROR: Error: Expected type guint8 for Argument 'data'
// but got type 'object'
// getAlbumArt/<#~/.local/share/gnome-shell/extensions
// /laine#knasher.gmail.com/streamMenu.js:42
var icon = GdkPixbuf.Pixbuf.new_from_inline(albumart, true);
callback(null, icon);
};
});
Here is the callback:
....
log('try retrieve albumart: ' + filePath);
if(GLib.file_test(iconPath, GLib.FileTest.EXISTS)){
let file = Gio.File.new_for_path(iconPath)
let icon = new Gio.FileIcon({file:file});
this._albumArt.gicon = icon;
} else if (filePath.indexOf('http') == 0) {
log('try retrieve from url: ' + filePath);
getAlbumArt(filePath, function(code, icon){
if (code) {
this._albumArt.gicon = icon;
} else {
this._albumArt.hide();
}
});
}
....
My question is, how to parse the response, which is a jpg image, so that I can set the widget icon with it?
Thank you very much!
I was able achieve this by simply doing:
const St = imports.gi.St;
const Gio = imports.gi.Gio;
// ...
this.icon = new St.Icon()
// ...
let url = 'https://some.url'
let icon = Gio.icon_new_for_string(url);
this.icon.set_gicon(icon);
And it will automatically download it.
I had been struggling for hours with this issue until I finally figured out a way to do it with a local image cache (downloading the image and storing it in an icons/ folder). Then I tried this approach for fun (just to see what would happen, expecting it to fail miserably), and guess what? It just worked. This is not mentioned anywhere in the very scarce documentation I was able to find.
For anyone still having the same problem here is my solution:
_httpSession.queue_message(request, function(_httpSession, message) {
let buffer = message.response_body.flatten();
let bytes = buffer.get_data();
let gicon = Gio.BytesIcon.new(bytes);
// your code here
});
How to make a picture from a base64-string to send it to server by using HttpRequest.request?
For example, I have the following base64-string:
'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
Instead of sending it I would like to post a jpeg to server? Is it possible?
Convert Base64 to bytes
How to native convert string -> base64 and base64 -> string
Upload binary as image
Dart how to upload image
EDIT
(this is the server part, I have to look for the client part)
Client code:
var request = new HttpRequest()
..open("POST", 'http://yourdomain.com/yourservice')
..overrideMimeType("image/your-imagetype") // might be that this doesn't work than use the next line
..setRequestHeader("Content-Type", "image/your-imagetype")
..onProgress.listen((e) => ...);
request
..onReadyStateChange.listen((e) => ...)
..onLoad.listen((e) => ...)
..send(yourBinaryDataAsUint8List);
Convert to image:
I think you need to create a dataURL like show here How to upload a file in Dart?
and then use the created dataUrl as src in code like shown here How to load an image in Dart
see also Base64 png data to html5 canvas as #DanFromGermany mentioned in his comment on the question.
It may be necessary to convert List to Uint8List in between.
Please add a comment if you need more information.
I like decoding on server-side, but anyways.
Basically you just split a text you got from canvas.toDataUrl(), convert the Base64 text to binary data, then send it to server. Use "CryptoUtils" in "crypto" library to treat Base64. I haven't tested with any proper http server, but this code should work.
// Draw an on-memory image.
final CanvasElement canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
final CanvasRenderingContext2D context = canvas.getContext('2d');
final CanvasGradient gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, "#1e4877");
gradient.addColorStop(0.5, "#4584b4");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(10, 10);
context.lineTo(240, 240);
context.lineWidth = 10;
context.strokeStyle = '#ff0000';
context.stroke();
// Convert the image to data url
final String dataUrl = canvas.toDataUrl('image/jpeg');
final String base64Text = dataUrl.split(',')[1];
final Uint8ClampedList base64Data = new Uint8ClampedList.fromList(
CryptoUtils.base64StringToBytes(base64Text));
// Now send the base64 encoded data to the server.
final HttpRequest request = new HttpRequest();
request
..open("POST", 'http://yourdomain.com/postservice')
..onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print("onReadyStateChange: " + request.responseText); // output the response from the server
}
})
..onError.listen((_) {
print("onError: " + _.toString());
})
..send(base64Data);
I posted a complete snippet here. https://gist.github.com/hyamamoto/9391477
I found the Blob conversion part not to be working (anymore?).
The code from here does work:
Blob createImageBlob(String dataUri) {
String byteString = window.atob(dataUri.split(',')[1]);
String mimeString = dataUri.split(',')[0].split(':')[1].split(';')[0];
Uint8List arrayBuffer = new Uint8List(byteString.length);
Uint8List dataArray = new Uint8List.view(arrayBuffer.buffer);
for (var i = 0; i < byteString.length; i++) {
dataArray[i] = byteString.codeUnitAt(i);
}
Blob blob = new Blob([arrayBuffer], mimeString);
return blob;
}