Titanium - remote image can't display as background in Imageview - titanium-mobile

I have created an application in the alloy framework (Titanium). I get the image name and url for fetch image from the webserver. I set this fetched image as background of Imageview. It displays fine in an IPhone device and simulator but it does not display in an Android device and emulator. I used the code below:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
console.log("UPDATE PROFILE: "+this.responseText);
var result = JSON.parse(this.responseText);
if(result['success'] == 1) {
var data = result['data'];
$.imgNotification.image = Alloy.Globals.uploadImageURL+result['data']['picture'];
$.imgProfilePic.image = Alloy.Globals.uploadImageURL+result['data']['picture'];
$.imgProfilePic3.image = Alloy.Globals.uploadImageURL+result['data']['picture'];
}
};
xhr.onerror = function(e) {
Titanium.API.info('userLogin error: ' + e.error);
alert('Check your network connection');
};
xhr.open('POST', Alloy.Globals.webserviceURL);
xhr.send({method : 'getMyDetails', userid: userID});
A remote image is not display in android device.

Related

convert .heic image to jpg image format in laravel

I have added intervention/image package to convert image format in laravel.
image converted successfully but after uploading image quality was so bad.
Original Image
Uploaded Image
$img =(string) Image::make($image['base64'])
->resize(500, 500)->encode('jpg',100);;
$img = base64_encode($img);
To convert Heic image you have to use imagick, can you use this instead
This is how to install https://ourcodeworld.com/articles/read/645/how-to-install-imagick-for-php-7-in-ubuntu-16-04
try {
$image = new \Imagick();
$image->readImageBlob($image['base64']));
$image->setImageFormat("jpeg");
$image->setImageCompressionQuality(100);
$image->writeImage($targetdir.$uid.".jpg");
}
catch (\ImagickException $ex) {
/**#var \Exception $ex */
return new JSONResponse(["error" => "Imagick failed to convert the images, check if you fulfill all requirements." , "details" => $ex->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
A bit late, but I had the same problem.
I managed to do it with the heic2any js library (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)
I converted the picture on client side, then gave it to the input in client side.
Server is seeing it as it was originally uploaded as jpg.
function convertHeicToJpg(input)
{
var fileName = $(input).val();
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if(fileNameExt == "heic") {
var blob = $(input)[0].files[0]; //ev.target.files[0];
heic2any({
blob: blob,
toType: "image/jpg",
})
.then(function (resultBlob) {
var url = URL.createObjectURL(resultBlob);
$(input).parent().find(".upload-file").css("background-image", "url("+url+")"); //previewing the uploaded picture
//adding converted picture to the original <input type="file">
let fileInputElement = $(input)[0];
let container = new DataTransfer();
let file = new File([resultBlob], "heic"+".jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
container.items.add(file);
fileInputElement.files = container.files;
console.log("added");
})
.catch(function (x) {
console.log(x.code);
console.log(x.message);
});
}
}
$("#input").change(function() {
convertHeicToJpg(this);
});
What I am doing is converting the heic picture to jpg, then previewing it.
After that I add it to the original input. Server side will consider it as an uploaded jpg.
Some delay can appear while converting, therefore I placed a loader gif while uploading.
The heic2any js library helped me accomplish this (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)
On the client side, I converted the picture, then gave it to the server input. The server sees it as it was originally uploaded as PNG.
$('#files').on('change' , function(){
var total_file=document.getElementById("files").files.length;
for(var i=0;i<total_file;i++)
{
files = event.target.files[i];
var fileName = files.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
objURL = URL.createObjectURL(event.target.files[i]);
if(fileNameExt == "heic") {
objURL = await convertHeicToJpg(input , i);
}
})
async function convertHeicToJpg(input , i)
{
var blobfile = $(input)[0].files[i]; //ev.target.files[0];
let blobURL = URL.createObjectURL(blobfile);
// convert "fetch" the new blob url
let blobRes = await fetch(blobURL)
// convert response to blob
let blob = await blobRes.blob()
// convert to PNG - response is blob
let resultBlob = await heic2any({ blob })
console.log(resultBlob)
var url = URL.createObjectURL(resultBlob);
let fileInputElement = $(input)[0];
let container = new DataTransfer();
let file = new File([resultBlob], "heic"+".png",{type:"image/png", lastModified:new Date().getTime()});
container.items.add(file);
fileInputElement.files[0] = container.files;
uploadFile(container.files);
console.log("added");
console.log(url);
return url ;
}
function uploadFile(files)
{
console.log(files);
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
form_data.append("files[]", files[count]);
}
$.ajax({
url:"<?php echo base_url(); ?>Property/upload",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
dataType:'JSON',
beforeSend:function(){
//..processing
},
success:function(data)
{
alert('image uploade')
}
})
}

Creating An Image Download Chrome Extension

I am creating a chrome extension that downloads all the images on the current webpage and this is what I have
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
downloadImages()
}, false);
}, false);
function downloadImages() {
var images = document.getElementsByTagName('img');
var srcList = [];
var i = 0;
setInterval(function(){
if(images.length > i){
srcList.push(images[i].src);
var link = document.createElement("a");
link.id=i;
link.download = images[i].src;
link.href = images[i].src;
link.click();
i++;
}
},1500);
}
This adds a click listener that should download all images when you click the button on the other section. I know this code works because I replaced the code that downloads the images with the code for an alert and when I pressed the button it indeed made an alert, so why is it that when I add the image downloading code it doesn't do anything? Also I have tested the image downloading code, it works.

Dropzone sailsjs nodejs upload image NetworkError: 404 Not Found

I use Sails.js, which is based on Node.js. For the upload I use Dropzone. To display the pictures I use owl-carousel.
When I add a new picture and I try to display it I receive the following error:
"NetworkError: 404 Not Found - http://localhost:1337/superrare/b004421de079bb2531cc5cd6346d202d/dde8221dc9e0b750479cedd3924af191/dde8221dc9e0b750479cedd3924af191.png"
If I open the above link in another tab I can see the image, because it exists at the specific path.
If I refresh the page I can see the picture in the owl carousel, with the same path that is displayed above.
If I modify the Dropzone code for testing purposes, on success add to carousel an older picture, the picture will be displayed -> imagePath = '/superrare/b004421de079bb2531cc5cd6346d202d/d845a68e5a57acf2f879bcd50966cc11/d845a68e5a57acf2f879bcd50966cc11.png';
So only when I try to add a new picture path I receive a 404 error...
If I add a delay of 5 seconds, the error is the same 404.
Here is my code
Dropzone.options.mydropzone = {
autoProcessQueue: false,
init: function () {
var imageName, imagePath, imageID;
var submitButton = document.querySelector("#submit-all");
myDropzone = this; // closure
this.on("success", function (file, responseJson) {
imageName = responseJson.createdAt;
imagePath = responseJson.path;
//imagePath = '/superrare/b004421de079bb2531cc5cd6346d202d/d845a68e5a57acf2f879bcd50966cc11/d845a68e5a57acf2f879bcd50966cc11.png';
imageID = responseJson.id;
var content = '<div class="item"><div id="visinput" class="container-img">'+
'<img file-id="' + imageID + '" src="' + imagePath + '">'+
'</div></div>';
// get owl element
var owl = $("#owlUpload");
// add item to owl carousel
setTimeout(function () {
owl.data('owlCarousel').addItem(content);
}, 5000);
document.getElementById("serverFile").value = fileProcess;
});
},
paramName: "file",
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};

Cordova - Insert to web page's database

I'm developing an app using Apache Cordova for Visual Studio. The purpose of this app is to take a picture using the phone and upload this picture alongside with some other user input data to our company's webpage, that uses a SQL-server Database to store it's data.
So, the question is: How can I insert data to this database so I can show it on the webpage, considering that the app will be used outside of our network? So it can't be a local connection to our database!
var pictureSource;
var destinationType;
document.addEventListener("deviceready", onDeviceReady, false);
On device ready
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
Clean Up
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
Upload photo taken from camera
function onCapturePhoto(fileURI) {
document.getElementById('MyElement').innerHTML = 'Uploading....';
var win = function (r) {
clearCache();
retries = 0;
document.getElementById('MyElement').innerHTML = '';
alert('Image Uploaded! Successfully');
};
var fail = function (error) {
if (retries === 0) {
retries++;
setTimeout(function () {
document.getElementById('MyElement').innerHTML = '';
onCapturePhoto(fileURI);
}, 1000);
} else {
retries = 0;
clearCache();
document.getElementById('MyElement').innerHTML = '';
alert('Something went wrong..Try Again');
}
};
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.params = {};
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://yourserver.com/phpfile.php"), win, fail, options);
}
function onFail(message) {
alert(message);
}
Function To Call The Camera
Take Picture
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 100,
destinationType: destinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG
});
}
Php part
<?php
$sourcePath = $_FILES['file']['tmp_name'];
$targetPath = "images/".$_FILES['file']['name']; // save uploaded image to images folder
move_uploaded_file($sourcePath,$targetPath) ;
?>
You will need to set up a secure API that has access to that database. Then, you can make an http POST from your Cordova app to an endpoint that saves the image in the database. You could use base64 encoding to facilitate the transfer of the image data. Then, you could read the images from the database just like usual!
All that you need to do on the Cordova side of things would be send an http request with your image data to the API server. You could do that with vanilla JS ala XMLHttpRequest, or with a Cordova plugin like this https://github.com/wymsee/cordova-HTTP.
The server side will be a bit more complicated, as you will need to create an API endpoint that saves the image data into your MS-SQL server. You should check out this high-level explanation: https://technet.microsoft.com/en-us/library/aa258693(v=sql.80).aspx. There are also Node.js interfaces for MS-SQL servers if that is your fancy.

Convert Blob to file and pass it as POST parameter XMLHttpRequest

//photo - image in Blob type
//no problems with it, checked with FileReader.readAsDataURL & <img>
var form = new FormData()
form.append('file1', photo, 'image.jpg')
ajax.post(url, form, callback) //no photos uploaded
Documentation of what I am trying to do: Uploading Files to the VK Server Procedure (step 2)
So, how should I pass my blob as POST parameter?
Image of the request
A complete File Upload exampe found at Mozilla Developer Network
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Uploading_a_user-selected_file
You use FileReader.readAsBinaryString() to read the data and then XHR sendAsBinary() to push IO forward
function FileUpload(img, file) {
var reader = new FileReader();
this.ctrl = createThrobber(img);
var xhr = new XMLHttpRequest();
this.xhr = xhr;
var self = this;
this.xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
self.ctrl.update(percentage);
}
}, false);
xhr.upload.addEventListener("load", function(e){
self.ctrl.update(100);
var canvas = self.ctrl.ctx.canvas;
canvas.parentNode.removeChild(canvas);
}, false);
xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
reader.onload = function(evt) {
xhr.sendAsBinary(evt.target.result);
};
reader.readAsBinaryString(file);
}

Resources