Why are dropzoneJS resize options having no affect? - dropzone.js

I have drop zone working in a rails 6 app with ActiveStorage and Stimulus. However, the resizeHeight and resizeQuality don't seem to have any affect on the uploaded image.
In the settings illustrated below, Im expecting the final image to be small with low quality. However, I get back the same image I originally attached. No compression or size changes at all.
Also, I'm curious if will DropzoneJS upsize? Or, if by default it will not upsize? Also, is it smart enough to skip resize options for non-images? The docs don't specify.
My Dropzone_controller looks like this:
import { Controller } from "stimulus"
import Dropzone from "dropzone"
import 'dropzone/dist/min/dropzone.min.css'
import 'dropzone/dist/min/basic.min.css'
import { DirectUpload } from "#rails/activestorage"
export default class extends Controller {
static targets = ["input"]
connect() {
Dropzone.autoDiscover = false
this.inputTarget.disable = true
this.inputTarget.style.display = "none"
const dropzone = new Dropzone(this.element, {
url: '/',
maxFiles: 10,
maxFilesize: 6,
addRemoveLinks: true,
resizeHeight: 50,
resizeQuality: 0.1,
autoQueue: false
})
dropzone.on("addedfile", file => {
setTimeout(() => {
if (file.accepted) {
const upload = new DirectUpload(file, this.url)
upload.create((error, blob) => {
this.hiddenInput = document.createElement("input")
this.hiddenInput.type = "hidden"
this.hiddenInput.name = this.inputTarget.name
this.hiddenInput.value = blob.signed_id
this.inputTarget.parentNode.insertBefore(this.hiddenInput, this.inputTarget.nextSibling)
dropzone.emit("success", file)
dropzone.emit("complete", file)
})
}
}, 500)
})
}
get url() {
return this.inputTarget.getAttribute('data-direct-upload-url')
}
}
Thanks!!!!

resizeWidth and resizeHeight have no effect because setting autoqueue: false bypasses this part of the Dropzone source code.

Related

CKEditor 5 - writer.setAttribute('title', ...) on img element doesn't work

I am creating a plugin for CKEditor 5, and I can't figure out how to set the title attribute on an <img> element using writer.setAttribute('title', ...).
I have tried stuff like schema.extend but to no avail.
The thing is, code works flawlessly when operating on the alt attribute.
Am I missing something?
My plugin code:
const ButtonView = require('#ckeditor/ckeditor5-ui/src/button/buttonview').default;
const imageIcon = require('#ckeditor/ckeditor5-core/theme/icons/low-vision.svg').default;
export default class ImageTextTitle extends Plugin {
init() {
const editor = this.editor;
editor.ui.componentFactory.add('imageTextTitle', locale => {
const view = new ButtonView(locale);
view.set({
label: 'Insert image title',
icon: imageIcon,
tooltip: true
});
view.on('execute', () => {
const newTitle = prompt('New image title');
const selection = editor.model.document.selection;
const imageElement = selection.getSelectedElement();
if (newTitle !== null) {
editor.model.change(writer => {
writer.setAttribute('title', newTitle, imageElement);
});
}
});
return view;
});
}
}

How use MediaFilePicker and PhotoEditor plugins in Nativescript

I am trying to use MediaFilePicker on nativescript and at the same time use the PhotoEditor plugin to crop/edit the photo taken from the camera but I don't make it work... here is part of my code:
let options: ImagePickerOptions = {
android: {
isCaptureMood: true, // if true then camera will open directly.
isNeedCamera: true,
maxNumberFiles: 1,
isNeedFolderList: true
}, ios: {
isCaptureMood: true, // if true then camera will open directly.
maxNumberFiles: 1
}
};
let mediafilepicker = new Mediafilepicker();
mediafilepicker.openImagePicker(options);
mediafilepicker.on("getFiles", function (res) {
let results = res.object.get('results');
let result = results[0];
let source = new imageSourceModule.ImageSource();
source.fromAsset(result.rawData).then((source) => {
const photoEditor = new PhotoEditor();
photoEditor.editPhoto({
imageSource: source,
hiddenControls: [],
}).then((newImage) => {
}).catch((e) => {
reject();
});
});
});
The result object of the FilePicker comes like:
{
"type": "capturedImage",
"file": {},
"rawData": "[Circular]"
}
I believe if the picture was taken from the camera, then use the rawData field, but I dont know which format is coming and how to give it to PhotoEditor pluging to play with it.
Any suggestions?
Thanks!
The issue was at this line source.fromAsset(result.rawData) here, result.rawData is not an ImageAsset but it's PHAsset. You will have to create an ImageAsset from PHAsset and pass it on to fromAsset. So it would look like,
import { ImageAsset } from "tns-core-modules/image-asset";
....
....
imgSource.fromAsset(new ImageAsset(img)).then((source) => {
const photoEditor = new PhotoEditor();
console.log(source === imgSource);
photoEditor.editPhoto({
imageSource: source,
hiddenControls: [],
}).then((newImage: ImageSource) => {
console.log('Get files...');
// Here you can save newImage, send it to your backend or simply display it in your app
}).catch((e) => {
//reject();
});
});

How to upload a base64 image to S3 with amplify, react native application

Looking for a simple example of how to upload a base64 image to aws S3 using amplify.
Assuming you configured Amplify Storage and set the permissions to public, here is a code example that uses Storage from Amplify to upload images to S3 bucket. The images are fetched from the local device using ImagePicker from Expo.
import React from 'react';
import {
StyleSheet,
ScrollView,
Image,
Dimensions } from 'react-native'
import { ImagePicker, Permissions } from 'expo'
import { Icon } from 'native-base'
import Amplify from '#aws-amplify/core'
import Storage from '#aws-amplify/storage'
import config from './aws-exports'
class App extends React.Component {
state = {
image: null,
}
// fetch a single image from user's device and save it to S3
useLibraryHandler = async () => {
await this.askPermissionsAsync()
let result = await ImagePicker.launchImageLibraryAsync(
{
allowsEditing: false,
//aspect: [4, 3],
}
)
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri })
this.uploadImage(this.state.image)
}
}
// add a single image to S3
uploadImage = async uri => {
const response = await fetch(uri)
const blob = await response.blob() // format the data for images
const folder = 'images'
const fileName = 'flower.jpeg'
await Storage.put(folder + '/' + fileName, blob, {
contentType: 'image/jpeg',
level: 'public'
}).then(data => console.log(data))
.catch(err => console.log(err))
}
render() {
let { image } = this.state
let {height, width} = Dimensions.get('window')
return (
<ScrollView style={{flex: 1}} contentContainerStyle={styles.container}>
<Icon
name='md-add-circle'
style={styles.buttonStyle}
onPress={this.useLibraryHandler}
/>
{/*
true && expression always evaluates to expression,
and false && expression always evaluates to false
*/}
{image &&
<Image source={{ uri: image }} style={{ width: width, height: height/2 }} />
}
</ScrollView>
);
}
}
The name of the image is hardcoded which is not good. But this is a very good start nonetheless.
This is a simple method for uploading multiple images. It should work for single image too.
import {Storage} from "aws-amplify";
UploadPhotos(SelectedImages) {
SelectedImages.forEach(async (element) => {
let name = element.filename;
let access = { level: "protected", contentType: "image/jpeg" };
let imageData = await fetch(element.uri);
let blobData = await imageData.blob();
try {
Storage.put(name, blobData, access);
} catch (err) {
console.log("UploadPhotos error: ", err);
}
});
}

How to upload image with FILE_URI distination to firebase storage in Ionic 2

I'm trying to upload captured image to firebase storage after edit it by some custom editor.
My problem under two cases:
Case1 : If I used this code, then I can upload the image but I can't use my custom editor
takePicture(){
let options: CameraOptions;
options = {
quality : 85,
destinationType: this.camera.DestinationType.DATA_URL,
sourceType : this.camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
this.currentOriginalImageUri = 'data:image/jpeg;base64,' + imageData;
this.currentDocumentImageUri = 'data:image/jpeg;base64,' + imageData;
});
}
Case2 : If I used this code, then I can use the function of custom editor but I can't upload my image
takePicture(){
let options: CameraOptions;
options = {
quality : 85,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType : this.camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
this.currentOriginalImageUri = imageData;
this.currentDocumentImageUri = imageData;
});
}
Note: This is my uploading function
private uploadPhoto(): void {
let loader = this.loadingCtrl.create({
content: ""
})
loader.present().then(_=>{
return this.myPhotosRef.child(this.generateUUID()).child('myPhoto.JPEG').putString(this.currentDocumentImageUri,firebase.storage.StringFormat.DATA_URL).then((savedPicture) => {
this.currentDocumentImageUri = savedPicture.downloadURL;
this.afd.list('/notesImages/').push({
note_id: this.appService.id,
url: this.currentDocumentImageUri,
date: new Date().toISOString()
});
});
}).then(_=>{
loader.dismiss();
this.viewCtrl.dismiss();
})
}
So is there any way to use the both cases?
You are saving image as a string in the database. If you want to upload a file using file path using the linked api (assuming data_url is not working for your custom editor)
Try put() instead of putString().
return this.myPhotosRef.child(this.generateUUID()).child('myPhoto.JPEG').put(this.currentDocumentImageUri).then((savedPicture) => {
// rest of code
});

Integrate jsPDF in Nativescript

I researched that using jsPDF, json response cna be converted into PDF and then can be downloaded. Is there any way to integrate JsPDF in nativescript application?
Check the following POC with jsPDF and NativeScript, you need to override some global variables required by jsPDF and install some packages from npm:
global['window'] = {
'document': {
'createElementNS': () => { return {} }
}
};
global['document'] = {
'createElement': (str) => { return {} }
};
global['navigator'] = {};
import * as base64 from 'base-64';
import * as utf8 from 'utf8';
import * as jsPDF from 'jspdf';
global['btoa'] = (str) => {
var bytes = utf8.encode(str);
return base64.encode(bytes);
};
Example: https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=8
By other hand, you can use a NativeScript shim for aotb / btoa functions, to avoid install more packages from npm (Only install jspdf and #types/jspdf): https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=13
As you can see in the logic of the component, you need to import the file and modify some global variables:
require('../base64')
global['window'] = {
'document': {
'createElementNS': () => { return {} }
},
'atob': global['atob']
};
global['document'] = {
'createElement': (str) => { return {} }
};
global['navigator'] = {};
It would be much better to create a fork of jsPDF with that solution.
And later you can create your PDF:
generatePDF() {
var doc = new jsPDF('p', 'pt');
doc.setFontSize(26);
doc.text(40, 50, "My first PDF with NativeScript!");
//Add image
doc.addImage(imgData, 'JPEG', 20, 90, 300, 300)
var base64 = doc.output('datauristring')
dialogs.alert({
title: "PDF - Base64",
message: base64,
okButtonText: "Copy text"
}).then(() => {
clipboard.setText(base64)
});
}

Resources