How do I get ImageResizer to load the source image? - react-native

I'm using react-native-image-resizer in my React Native app.
I've tried giving assetPath, pathURI, and image (see below) to ImageResizer, and always get the same message:
err on ImageResizer Unable to load source image from path
I've verified that uri64 does encode the file, so I know that the file path and URI are correct.
let maxWidth = 24;
let maxHeight = 24;
let compressFormat = "PNG";
let quality = 100; // only used for jpeg
let rotation = 0;
let outputPath = ".";
let options = {};
let keepMeta = false;
const assetPath = "../../../../../assets/Knob-54px.png"
const pathURI = "file://" + assetPath
const uri64 = Base64.encodeURI(pathURI );
const image = 'data:image/jpeg;base64,' + uri64;
console.log("uri64 ", uri64);
console.log("image ", image);
ImageResizer.createResizedImage(pathURI or assetPath or image, maxWidth, maxHeight,
'PNG', quality, rotation, outputPath)
//, keepMeta = false,
//options = {mode: 'contain'})
.then(response => {
console.log("response.uri ", response.uri)
console.log("response.path ", response.path)
console.log("response.name ", response.name)
console.log("response.size ", response.size)
// response.uri is the URI of the new image that can now be displayed, uploaded...
// response.path is the path of the new image
// response.name is the name of the new image with the extension
// response.size is the size of the new image
})
.catch(err => {
console.log("err on ImageResizer", err)
// Oops, something went wrong. Check that the filename is correct and
// inspect err to get more details.
});
Here's the source code on GitHub for the ImageResizer:
https://github.com/bamlab/react-native-image-resizer

Related

Is there a way to modify the buffer of a png in a pdf document?

For a few days now i have been trying to extract images from a pdf, modify them, and then replace them in my pdf document. It works perfectly when working with jpeg images, but when it comes to png... I'm able to modify the image and then save it correctly, but when changing the buffer in the pdf, it turns all black. So there's my code :
try {
(async () => {
let imageData = imgTab.type === 'jpg' ? imgTab.data : await savePng(imgTab);
console.log(imgTab.type);
let typeJimp = "image/png";
if(imgTab.type === 'jpg'){
typeJimp = "image/jpeg";
}
const img = await Jimp.read(imageData).then(async function (image) {
image.color([
{ apply: 'hue', params: [90] }]);
*//HERE, the image saved is okay! It is modified as I want it to be*
image.write("testimage"+objIdx+"."+imgTab.type);
let data = fs.readFileSync("testimage"+objIdx+"."+imgTab.type);
let bufferData = Buffer.from(data);
*//The problem is when i do this to replace the buffer of my original image*
pdfObject.contents = bufferData;
fs.writeFileSync('client/public/test_modified.pdf', await pdfDoc.save());
}).catch(function (err) {
//return Promise.reject(err);
console.log(err);
});
})();
}
The main code to extract the images can be found here : pdf-lib extract images
I don't know if there's something special to do to make the buffer work, but if you do, feel free :)
Thanks in advance !
////
Okay, so for now, i just use it that way :
const img = await Jimp.read(imageData).then(async function (image) {
image.color([
{ apply: 'hue', params: [90] }]);
let data = await image.getBufferAsync('image/jpeg')
var res = await pdfDoc.embedJpg(data);
res.ref = pdfRef;
var test = await res.embed();
fs.writeFileSync('client/public/test_modified.pdf', await pdfDoc.save());
})
My pdfRef is the ref of the initial object i was trying to modify.

How do I access the camera image so that I can send it via email?

I am trying to take a picture (ionic 4) and send this image as an email attachment. So the intention is to take a picture, save it and send the saved image as an email attachment.
I tried following an example I got from this site: https://devdactic.com/ionic-4-image-upload-storage/
takePicture () {
this.camera.getPicture(this.options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
this.filePath.resolveNativePath(imageData)
.then(filePath => {
// I am lost a this point.
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imageData.substring(imageData.lastIndexOf('/') + 1, imageData.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
this.sendMail(currentName);
});
//let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
you can add CameraOptions. To save the image to your gallery
by doing this:
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true
}
and use the image from your gallery to send the email

Save an image from URL, store on device, and open image successfully in RN

I'm having difficulty fetching an image from a url, storing the image on a device, and opening/viewing it successfully.
I am able to fetch the image successfully (I believe)
I transform the image into base64 using Buffer (npm buffer) and save it to the device using react-native-fs. I'm not sure the Buffer transformation is needed. I can stat the image and everything looks fine. When I use a FileManager application I downloaded and I click on the file the image is blank.
let response = await axios.request({
url: imgUrl
});
let idxStart = imgUrl.lastIndexOf('/');
let idxEnd = imgUrl.lastIndexOf('.');
let filename = imgUrl.substring(idxStart + 1, idxEnd) + '.jpg';
let path = RNFS.DocumentDirectoryPath + `/${filename}`
let base64data = new Buffer(response.data).toString('base64');
RNFS.writeFile(RNFS.PicturesDirectoryPath + '/' + filename, base64data, 'base64').then(() => {
RNFS.stat(path).then(info => {
console.log(info);
});
RNFS.readFile(RNFS.PicturesDirectoryPath + '/' + filename, 'base64').then(data => {
// console.log('data:', data);
});
} ,error => {
console.log('error writing file:', error)
}).catch(error => { console.log('error:', error)});
If anybody could provide a simple working example that'd be AWESOME!

Titanium - Get image file from filesystem on Android

I have a problem getting an image from filesystem. On iOS works fine.
First of all, I save a remote image in the filesystem with this function:
img.imagen = url from the remote image (e.g. http://onesite.es/img2.jpeg)
function descargarImagen(img, callback){
var path = img.imagen;
var filename = path.split("/").pop();
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
f.write(this.responseData); // write to the file
Ti.API.debug("-- Imagen guardada: " + f.nativePath);
callback({path: f.nativePath});
},
timeout: 10000
});
xhr.open('GET', path);
xhr.send();
}
Now, I want to share this image creating an Android Intent:
args.image = f.nativePath(in the previous function)
var intent = null;
var intentType = null;
intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_SEND
});
// add text status
if (args.status){
intent.putExtra(Ti.Android.EXTRA_TEXT, args.status);
}
// change type according to the content
if (args.image){
intent.type = "image/*";
intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);
}else{
intent.type = "text/plain";
intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
}
// launch intent
Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, args.androidDialogTitle));
What I'm doing wrong?

image in image (overlay image) with gm (GraphicsMagick)

I want to put a watermark picture (logo) on my resized pictures as you can see in the code below.
Can somebody help how to put a picture in the right low corner with a opacity of 50%?
var fs = require('fs')
, gm = require('gm');
function walk(currentDirPath, callback) {
var fs = require('fs'), path = require('path');
fs.readdirSync(currentDirPath).forEach(function(name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walk(filePath, callback);
}
});
}
var inputDir = "/Users/USER/Desktop/src/"
var outputDir = "/Users/USER/Desktop/target/"
walk(inputDir, function(filePath, stat) {
// match filename like IMG_1234.JPG
var filename = filePath.match(/IMG_\d{4}.JPG/gmi).toString();
console.log(filename);
var outputfile = outputDir + filename
var readStream = fs.createReadStream(filePath);
gm(readStream, filename)
.size({bufferStream: true}, function(err, size) {
this.resize(size.width / 2, size.height / 2)
this.write(outputfile, function (err) {
if (!err) console.log('done');
});
});
});
Here is the solution:
.draw(['image Over 0,0 0,0 /Users/USER/Desktop/target/nike-global-diversity-logo.png'])
put this line of code after gm call and before the resizing.