Save UIImage as jpg File in Photo Library Directory in Xamarin.iOS - file

As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.

How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});

Related

ReactJS file upload Axios

I am having form with 4 file upload fields, that users can submit up to 4 images.
I am adding files to array, loop and upload to server with PHP.
Now everything seams to be working fine.. but returned image names (I am using those to store in DB) are not in the same order as I am uploading them:
Here is example of code:
if (postImage1 !== null) {
postImagesArray.push(postImage1);
}
if (postImage2 !== null) {
postImagesArray.push(postImage2);
}
if (postImage3 !== null) {
postImagesArray.push(postImage3);
}
if (postImage4 !== null) {
postImagesArray.push(postImage4);
}
//Loop Array and make upload......
var startCount = 1;
var endCount = postImagesArray.length;
for (var i = 0; i < postImagesArray.length; i++) {
var currentImage = postImagesArray[i];
//##### UPLOADING IMAGE ###########
try {
var base_url = 'https://##############.com/uploadImage.php';
var fd = new FormData();
fd.append('avatar', currentImage, 'post.jpg');
axios.post(base_url, fd).then((res) => {
console.log(res);
if (res.data.status === 'success') {
let fileConstruct =
'https://############.com/' +
res.data.fileName +
'?fit=crop&w=840&q=80';
uploadImagesArray.push(fileConstruct);
} else {
// there was an error with file upload... revert to default...
console.log('No error but no image either......');
}
if (startCount == endCount) {
uploadImagesConstruct();
}
startCount++;
});
} catch (err) {
//console.error(err);
console.log(
'There was an error uploading file to the web server: ' + err
);
if (startCount == endCount) {
uploadImagesConstruct();
}
}
Interesting thing is, images are mixed up always in the same order... (so it is not random), instead of returned image1,image2,image3,image4 I am getting image3, image2, image4, image1....If I post only 2 images it is image2,image1.... so first image is always returned last.....
Can anybody see what I am doing wrong..
Thanks!!!!
If anyone need this in the future....
I simply added underscore and postion in the loop "_i" before ".jpg" when I am constructing file names..
fd.append('avatar', currentImage, 'post.jpg');
now is:
fd.append('avatar', currentImage, `post_${i}.jpg`);
and since I am putting all records in the array
uploadImagesArray.push(fileConstruct);
I just resorted it.. by the numbers I added..
uploadImagesArray.sort(function(x, y) {
var xp = x.substring(x.lastIndexOf('_') + 1, x.lastIndexOf('.jpg'));
var yp = y.substring(y.lastIndexOf('_') + 1, y.lastIndexOf('.jpg'));
return xp == yp ? 0 : xp < yp ? -1 : 1;
});

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Rendering a child page in a parent page

is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan
Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}

How do you upload an image file to mongoose database using mean js

I am new to the mean stack. I want to know how to upload an image file to the database(mongoose) through angularjs. If possible, please provide me with some code. I have searched the internet but I haven't found any suitable code.
You have plenty ways and tools to achieve what you want. I put one of them here:
For this one I use angular-file-upload as client side. So you need this one in your controller:
$scope.onFileSelect = function(image) {
if (angular.isArray(image)) {
image = image[0];
}
// This is how I handle file types in client side
if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
alert('Only PNG and JPEG are accepted.');
return;
}
$scope.uploadInProgress = true;
$scope.uploadProgress = 0;
$scope.upload = $upload.upload({
url: '/upload/image',
method: 'POST',
file: image
}).progress(function(event) {
$scope.uploadProgress = Math.floor(event.loaded / event.total);
$scope.$apply();
}).success(function(data, status, headers, config) {
$scope.uploadInProgress = false;
// If you need uploaded file immediately
$scope.uploadedImage = JSON.parse(data);
}).error(function(err) {
$scope.uploadInProgress = false;
console.log('Error uploading file: ' + err.message || err);
});
};
And following code in your view (I also added file type handler for modern browsers):
Upload image <input type="file" data-ng-file-select="onFileSelect($files)" accept="image/png, image/jpeg">
<span data-ng-if="uploadInProgress">Upload progress: {{ uploadProgress }}</span>
<img data-ng-src="uploadedImage" data-ng-if="uploadedImage">
For server side, I used node-multiparty.
And this is what you need in your server side route:
app.route('/upload/image')
.post(upload.postImage);
And in server side controller:
var uuid = require('node-uuid'),
multiparty = require('multiparty'),
fs = require('fs');
exports.postImage = function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('.');
var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
// uuid is for generating unique filenames.
var fileName = uuid.v4() + extension;
var destPath = 'path/to/where/you/want/to/store/your/files/' + fileName;
// Server side file type checker.
if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
fs.unlink(tmpPath);
return res.status(400).send('Unsupported file type.');
}
fs.rename(tmpPath, destPath, function(err) {
if (err) {
return res.status(400).send('Image is not saved:');
}
return res.json(destPath);
});
});
};
As you can see, I store uploaded files in file system, so I just used node-uuid to give them unique name. If you want to store your files directly in database, you don't need uuid, and in that case, just use Buffer data type.
Also please take care of things like adding angularFileUpload to your angular module dependencies.
I got ENOENT and EXDEV errors. After solving these, below code worked for me.
var uuid = require('node-uuid'),
multiparty = require('multiparty'),
fs = require('fs');
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
var contentType = file.headers['content-type'];
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('.');
var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
// uuid is for generating unique filenames.
var fileName = uuid.v4() + extension;
var destPath = appRoot +'/../public/images/profile_images/' + fileName;
// Server side file type checker.
if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
fs.unlink(tmpPath);
return res.status(400).send('Unsupported file type.');
}
var is = fs.createReadStream(tmpPath);
var os = fs.createWriteStream(destPath);
if(is.pipe(os)) {
fs.unlink(tmpPath, function (err) { //To unlink the file from temp path after copy
if (err) {
console.log(err);
}
});
return res.json(destPath);
}else
return res.json('File not uploaded');
});
for variable 'appRoot' do below in express.js
path = require('path');
global.appRoot = path.resolve(__dirname);

Get Count of selected files in Telerik Upload

I need to get a count of all selected files using Telerik MVC Upload Control. Can anyone tell me how can i do that. I tried code like this.
var count = e.files.length;
But its counting always as one.
try this code
[function onSelect(e) {
var selectedFiles = e.files.length;
totalFiles += selectedFiles;
}
function UploadRemove(e) {
totalFiles--;
if (totalFiles > 0) {
// Write true block code here.
}
else if (totalFiles == 0) {
// Write your false block code here.
}
}]
You could do this in your upload event handler:
upload: function (e) {
// File Count:
var fileCount = this.wrapper.find(".k-file").length;
// File Index:
var uid = e.files[0].uid;
var file = this.wrapper.find(".k-file[data-uid='" + uid + "']");
var fileIndex = file.index();
}

Resources