I have a scenario where I need to save an image from the <Image /> tag to the local file. The code does save the image to the file but i get an empty image, I know it's sound simple but I am new to NS and couldn't find anything on google, maybe someone knows why?
XML:
<page>
<image src="pic.png" id="img"/>
</page>
JS:
let img = page.getViewById("img");
let path = fs.path.join(fs.knownFolders.documents().path, "pic.png");
let src = ImageSource.fromNativeSource(img);
let saved = src.saveToFile(path, "png");
you might be getting empty image because of saving image before it is fully loaded. try saving image after it is fully loaded as shown in below snippet.
To save image after it's load we are using loaded event and isLoading property of the Image.
XML:
<page>
<image src="pic.png" loaded="onImageLoaded" id="img"/>
</page>
TS:
onImageLoaded(args) {
console.log(args.eventName);
console.log(args.object);
var img = args.object;
console.log("img.isLoading: " + img.isLoading);
console.log("img.isLoaded: " + img.isLoaded);
if(img.isLoading){
img.on("isLoadingChange", function (args) {
console.log("isloading",args.value);
console.log("isloaded",args.object.isLoaded);
let img = args.object;
let path = fs.path.join(fs.knownFolders.documents().path, "pic.png");
let src = ImageSource.fromNativeSource(img);
let saved = src.saveToFile(path, "png");
});
}else if(!img.isLoading&&img.isLoaded){
let path = fs.path.join(fs.knownFolders.documents().path, "pic.png");
let src = ImageSource.fromNativeSource(img);
let saved = src.saveToFile(path, "png");
}else{
console.log("image loading failed");
}
}
Related
I've written a function that should produce a random image from an array in Javascript.
I'm wanting to execute the function with an html button. I've written the code but it doesn't work. The image should be directed to a flex box div.
Code
var myImages=
["https://picsum.photos/536/354","Images/IMG_4830.jpeg","Images/IMG_4338.jpeg",
"Images/IMG_4096.JPG"];
function randomImages(){
var rnd = Math.floor(Math.random()*myImages.length);
if(rnd == 0){
rnd = 1;
}
var image = document.createElement("img");
var div=document.getElementById("flex-box-create").src = myImages[rnd]
div.appendChild(image)
}
button = <div><button class="btn btn-primary" id="image-Generator"
onclick="randomImages()">Click</button></div>
thanks
The source should be set on the image not the div, try this:
var image = document.createElement("img");
image.src = myImages[rnd];
var div = document.getElementById("flex-box-create");
div.appendChild(image);
I am trying to convert the image into base64 but I get a null result, anyone has a clue? I found few examples how to take a pic from a camera and convert into b64 but i couldn't found anything how to convert image tag into b64.
<image #loaded="loaded" src="myimg.jpg">
var ImageSourceModule = require("tns-core-modules/image-source");
function loaded(args){
let imageSource = ImageSourceModule.fromNativeSource(args.object.nativeElement);
console.log(imageSource.toBase64String('jpeg'))
}
you might be getting null data because of coverting image before it is fully loaded. try converting image after it is fully loaded as shown in below snippet.
To convert image after it's load we are using loaded event and isLoading property of the Image.
loaded(args) {
console.log(args.eventName);
console.log(args.object);
var img = args.object;
console.log("img.isLoading: " + img.isLoading);
console.log("img.isLoaded: " + img.isLoaded);
if(img.isLoading){
img.on("isLoadingChange", function (args) {
console.log("isloading",args.value);
console.log("isloaded",args.object.isLoaded);
let img = args.object;
let imageSource= ImageSource.fromNativeSource(img);
console.log(imageSource.toBase64String('jpeg'))
});
}else if(!img.isLoading&&img.isLoaded){
let imageSource= ImageSource.fromNativeSource(img);
console.log(imageSource.toBase64String('jpeg'))
}else{
console.log("image loading failed");
}
}
UPDATE
now its working, see the answer below (https://stackoverflow.com/a/43983621/2844901)
this is my getDrawing function, I need to save the signature from drawing to a file in file system, I've tried everything and I cant get the saveToFile demo in nativescript docs to get it work.
exports.getDrawing = function(args) {
var pad = frameModule.topmost().currentPage.getViewById("drawingPad");
// then access the 'drawing' property (Bitmap on Android) of the signaturepad
var img = frameModule.topmost().currentPage.getViewById("imagesignature");
pad.getDrawing().then(function(result){
img.src = result; // <-- this shows in an image label the drawing signature
########### this part should be save the file,but I don't get any error, and it doesn't save it to a file, when tried to dump "img" ############
var img2 = imageSource.fromAsset(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
});
}
the problem was, the getDrawing() does not return a promise it returns an image so the correct code should be a NativeSource.
pad.getDrawing().then(function(result){
img.src = result;
console.log("1");
var img2 = imageSource.fromNativeSource(result);
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = img2.saveToFile(path, "png");
console.log("saved: " + saved);
console.log("IMAGEN SRC.....");
});
can anyone please help me how to download remote image to mobile using nativescript android app?
For example,
<StackLayout>
<Image [src]="remoteImgUrl"></Image>
<Label tap="downloadImg({{remoteImgUrl}})" text="Download">
</StackLayout>
when user clicks on 'Download' I need to save that image in android device.
here is an example based on this app here:
TypeScript
export function saveFile(res: ImageSource) {
fileName = "some-image-name" + ".jpeg";
var folderPath;
if (application.android) {
var androidDownloadsPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
folderPath = fileSystem.path.join(androidDownloadsPath, "MyImages");
}
var folder = fileSystem.Folder.fromPath(folderPath);
var path = fileSystem.path.join(folderPath, fileName);
var exists = fileSystem.File.exists(path);
if (!exists) {
var saved = res.saveToFile(path, enums.ImageFormat.jpeg);
}
}
The method accepts imageSource as a parameter so you can call it with fromUrl method for imageSource e.g.
import * as imageSource from "image-source";
imageSource.fromUrl(IMAGE_URL_HERE)
.then(res => {
saveFile(res); //
})
I have an array with some NSImages in it.
I mainly want to convert NSImage to PDF. So, can anyone show me how to do it in Swift.
If possible, could you guys show me how to merge PDFs into one and output it as well?
Thank you so much.
Here are some rough steps to create a PDF document from images, this should get you started.
Use PDFKit (import Quartz) framework.
// Create an empty PDF document
let pdfDocument = PDFDocument()
// Load or create your NSImage
let image = NSImage(....)
// Create a PDF page instance from your image
let pdfPage = PDFPage(image: image!)
// Insert the PDF page into your document
pdfDocument.insert(pdfPage!, at: 0)
// Get the raw data of your PDF document
let data = pdfDocument.dataRepresentation()
// The url to save the data to
let url = URL(fileURLWithPath: "/Path/To/Your/PDF")
// Save the data to the url
try! data!.write(to: url)
You may need to tinker with the page's bounds and image size's to get the exact PDF page sizes you need.
You can use other PDFDocument/PDFPage API to insert, remove and reorder pages.
This Works well for me in swift(IOS 9 or above) :
func createPDF(images: [UIImage]) {
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
for image in images {
let imgView = UIImageView.init(image: image)
UIGraphicsBeginPDFPageWithInfo(imgView.bounds, nil)
let context = UIGraphicsGetCurrentContext()
imgView.layer.render(in: context!)
}
UIGraphicsEndPDFContext()
//try saving in doc dir to confirm:
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let path = dir?.appendingPathComponent("file.pdf")
do {
try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
} catch {
print("error catched")
}
let documentViewer = UIDocumentInteractionController(url: path!)
documentViewer.name = "Vitul"
documentViewer.delegate = self
documentViewer.presentPreview(animated: true)
}
Hope this will help someone :)