Итак, у меня есть компонент в Salesforce, который позволяет пользователям загружать изображения из свойств. Сначала единственная функциональность javascript заключалась в том, чтобы загружать изображения в службу хранения Google, но они попросили вставить водяной знак вместе с изображениями. Теперь javascript вставляет водяной знак перед загрузкой изображения, но иногда в зависимости от размера изображения они не соответствуют друг другу. Мои знания JavaScript действительно просты, и я, честно говоря, не знаю, как изменить размер водяного знака на основе загруженного изображения.
Javascript:
var DocumentCreator = function(params) {
var self = this;
self.maxStringSize = 6000000; // Maximum String size is 6,000,000 characters
self.maxFileSize = 4350000; // After Base64 Encoding, this is the max file size
self.chunkSize = 262144; // Google cloud recommended chunk size
self.startLoadingCallback = params.startLoading;
self.stopLoadingCallback = params.stopLoading;
self.displayChunkCallback = params.displayChunk;
self.apexController = params.apexController;
self.recordId = params.recordId;
// Chunks for broken uploads
self.currentPart = 0;
self.totalParts;
self.chunkSizeToSend;
self.fileId;
self.fileName;
self.fileSize;
self.fileSizeBase64;
self.attachment;
self.attachmentBase64;
self.attachmentBody;
self.positionIndex;
self.isDoneUploading;
// Google Storage Resumable upload API
self.isResumableUploadAvailable = window.OBJECT_TYPE == 'Property__c';
self.isResumableUpload;
self.remoteActionBuffer = {buffer: true, escape: true, timeout: 120000};
var IMAGE_TOO_LARGE = 'La imagen es demasiado grande. Por favor, elija una mas pequeña.';
var PLEASE_CHOOSE_IMAGE = 'Por favor eliga una imagen.';
var ERROR_READING = 'Error al leer el archivo.';
var SUCCESS = 'success';
var WARNING = 'warning';
var RENEWED = 'renewed';
var EXCEPTION = 'exception';
self.uploadFilesToPage = function(files) {
self.startLoadingCallback();
if (files.length && files[0]) {
var file = files[0];
if (file.size <= self.maxFileSize) {
self.attachmentName = file.name;
var originalFileReader = new FileReader();
originalFileReader.readAsDataURL(file);
originalFileReader.onloadend = function(e) {
var originalImage = document.createElement("img");
originalImage.src = originalFileReader.result;
watermark([originalImage, window.watermarkLogoURL])
.blob(watermark.image.center(0.5))
.then(function (blobResult) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
self.attachment = this.result;
self.attachmentBase64 = window.btoa(this.result);
if (self.isResumableUploadAvailable) {
self.fileSize = self.attachment.length;
} else {
self.fileSize = self.attachmentBase64.length;
}
self.totalParts = Math.ceil(self.fileSize / self.chunkSize);
self.positionIndex = 0;
self.isDoneUploading = false;
if (self.fileSize < self.maxStringSize) {
self.createDocument(null);
} else {
self.stopLoadingCallback(IMAGE_TOO_LARGE);
}
}
fileReader.onerror = function(e) {
self.stopLoadingCallback(ERROR_READING);
}
fileReader.onabort = function(e) {
self.stopLoadingCallback(ERROR_READING);
}
console.log(this.result);
console.log(typeof this.result);
fileReader.readAsBinaryString(blobResult);
}
);
}
} else {
self.stopLoadingCallback(IMAGE_TOO_LARGE);
}
} else {
self.stopLoadingCallback(PLEASE_CHOOSE_IMAGE);
}
};
...
Страница компонента:
<apex:component >
<apex:attribute name="recordId" description="Record Id of the parent standard page." type="String" required="true"/>
<apex:attribute name="pictures" description="Picture URLs loaded from Documents." type="PublicPicture__c[]" required="true"/>
<apex:attribute name="objectType" description="Parent object type." type="String" required="true"/>
<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" lang="en">
<head>
<apex:slds />
<apex:stylesheet value="{!URLFOR($Resource.PublicPicturesUpload, 'lib/slick/slick.css')}"/>
<apex:stylesheet value="{!URLFOR($Resource.PublicPicturesUpload, 'lib/slick/slick-theme.css')}"/>
<apex:stylesheet value="{!URLFOR($Resource.PublicPicturesUpload, 'css/main.css')}"/>
</head>
<body class="slds-scope">
<div id="presentation-container" style="width:1px;min-width:100%;overflow:hidden;">
<div id="loading-overlay">
<p id="chunkText" style="margin-top:9rem;text-align:center;display:none;">
Hemos detectado una imagen muy grande. Espera hasta que todas las partes estén subidas:
<span id="chunkPercentage"></span>
</p>
</div>
<div class="image-carousel">
<apex:repeat value="{!pictures}" var="picture">
<div>
<div class="img-container">
<img src="//images.weserv.nl/?url={!picture.URL__c}&h=300&w=300"/>
<apex:outputPanel rendered="{!objectType == 'Property__c'}">
<div data-location="" class="ppt-button" onclick="top.location='{!$Site.BaseUrl}'+'/apex/PropertyPicturesPresentation?id='+'{!recordId}&position='">
<svg class="slds-icon slds-icon_x-small slds-icon-text-default" aria-hidden="true">
<use xlink:href="{!URLFOR($Asset.SLDS, 'assets/icons/utility-sprite/svg/symbols.svg#expand_alt')}"></use>
</svg>
</div>
</apex:outputPanel>
</div>
</div>
</apex:repeat>
<apex:outputPanel rendered="{!pictures.size == 0}">
<div>
<img src="{!URLFOR($Resource.PublicPicturesUpload, 'img/srl-placeholder.jpeg')}"/>
</div>
</apex:outputPanel>
</div>
<div class="slds-m-top_small slds-grid">
<div class="slds-col"><!-- Fullscreen --></div>
<div class="slds-col">
<apex:outputPanel rendered="{!objectType = 'Property__c'}">
<a href="{!URLFOR('/apex/OrderPropertyPublicPictures', null, [id=recordId])}">Ordenar imágenes</a>
</apex:outputPanel>
<apex:outputPanel rendered="{!objectType = 'LandingPage__c'}">
<a href="{!URLFOR('/apex/OrderLandingPublicPictures', null, [id=recordId])}">Ordenar imágenes</a>
</apex:outputPanel>
<apex:outputPanel rendered="{!objectTYpe = 'LandingRegion__c'}">
<a href="{!URLFOR('/apex/OrderLandingRegionPublicPictures', null, [id=recordId])}">Ordenar imágenes</a>
</apex:outputPanel>
</div>
</div>
<div class="slds-m-top_small slds-coll slds-size_1-of-1">
<div class="slds-card attWrapper">
<div class="slds-card__header slds-grid">
<h2 class="slds-text-heading_small slds-truncate">Añadir una nueva imagen</h2>
</div>
<div class="slds-card__body slds-text-align_center">
<div class="slds-grid slds-wrap">
<div class="slds-col slds-size_1-of-2">
<div class="placeholder" id="dropzone">
<svg class="slds-icon slds-icon_large slds-icon-text-default" aria-hidden="true">
<use xlink:href="{!URLFOR($Asset.SLDS, 'assets/icons/utility-sprite/svg/symbols.svg#copy')}"></use>
</svg>
<div>Arrastre aquí la imagen</div>
</div>
</div>
<div class="slds-col slds-size_1-of-2 selectBtn">
<div>o si lo prefiere, seleccione un archivo</div>
<div class="slds-form-element slds-m-horizontal_medium" id="clickHere">
<input type="file" class="file" style="display:none" id="attachmentFile"/>
<div class="slds-button slds-button_neutral" style="cursor:pointer;" onclick="$('#attachmentFile').click();">Añadir imagen</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="spinner-wrapper">
<div role="status" class="slds-spinner slds-spinner_medium slds-spinner_brand">
<span class="slds-assistive-text">Loading</span>
<div class="slds-spinner__dot-a"></div>
<div class="slds-spinner__dot-b"></div>
</div>
</div>
<canvas id="canvas" style="display: none"></canvas>
<img id="imageContainer" class="hiddenElement"/>
<apex:includeScript value="{!URLFOR($Resource.PublicPicturesUpload, 'lib/jquery/jquery-3.2.1.min.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.PublicPicturesUpload, 'lib/slick/slick.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.SharedLibraries, 'watermarkjs/watermark.js')}"/>
<script type="text/javascript">
window.recordId = '{!recordId}';
window.OBJECT_TYPE = '{!objectType}';
window.watermarkLogoURL = "{!URLFOR($Resource.SharedLibraries, 'watermarkjs/img/watermark_logo.png')}";
</script>
<apex:includeScript value="{!URLFOR($Resource.PublicPicturesUpload, 'js/main.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.PublicPicturesUpload, 'js/documentCreator.js')}"/>
</body>
</html>
</apex:component>