Is there any equivalent of
Clipboard.GetImage().Save(FileName, Imaging.ImageFormat.Jpeg)
for UWP (Windows Universal Platform)?
I.e. saving the graphics image from clipboard into jpg format to file.
I am looking for example in vb.net/C#.
I have already started with
Dim datapackage = DataTransfer.Clipboard.GetContent()
If datapackage.Contains(StandardDataFormats.Bitmap) Then
Dim r As Windows.Storage.Streams.RandomAccessStreamReference = Await datapackage.GetBitmapAsync()
...
but I do not know how to continue (and even if I have even started correctly).
The first step is to try and get the image from the clipboard, if it exists:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
IRandomAccessStreamReference imageReceived = null;
try
{
imageReceived = await dataPackageView.GetBitmapAsync();
}
catch (Exception ex)
{
}
If it exists, launch a file save picker, choose where to save the image, and copy the image stream to the new file.
if (imageReceived != null)
{
using (var imageStream = await imageReceived.OpenReadAsync())
{
var fileSave = new FileSavePicker();
fileSave.FileTypeChoices.Add("Image", new string[] { ".jpg" });
var storageFile = await fileSave.PickSaveFileAsync();
using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await imageStream.AsStreamForRead().CopyToAsync(stream.AsStreamForWrite());
}
}
}
}
Related
I am having a problem with showing progress bar using nuget package (Acr.UserDialog) in xamarin forms iOS. with the same code snippet, its working well in Android platform.
using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black)) {
await Task.Run(() => {
// Code Logic Goes here ...
});
}
A version of ACR UserDialogs Library:
PCL Project - v6.5.1
iOS Project - v7.0.0
if anyone knows the solution for this issue, please provide a solution.
https://forums.xamarin.com/discussion/67832/implementing-file-picker-example-into-a-cross-platform-application
Please check this:
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
var fileFullName = file.FilePath.Substring(file.FilePath.LastIndexOf('\\') + 1);
var extension = Path.GetExtension(file.FileName).Substring(1);
var fileName = Path.GetFileNameWithoutExtension("Pick_" + extension + "_File_" + DateTime.UtcNow.ToString("MMddyyyy_hhmmss"));
using (Stream stream = file.GetStream())
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
filePath = ms.ToArray().SaveAttachmentInLocalFolder(fileName, extension);
}
}
public async Task GetPdfDataAsync(byte[] fileBytes)
{
try
{
var localPath = string.Empty;
var fileName = Guid.NewGuid().ToString();
localPath =
Task.Run(() => _localFileProvider.SaveFileToDisk(fileBytes, $"{fileName}.pdf")).Result;
if (string.IsNullOrWhiteSpace(localPath))
{
await PageDialogService.DisplayAlertAsync("Error loading PDF", "Computer says no", "OK");
return;
}
if (Device.RuntimePlatform == Device.Android)
Pdfviewsource = $"file:///android_asset/pdfjs/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}";
else
{
Pdfviewsource = localPath;
}
}
catch (Exception) { }
}
I have some data to save into a database.
I have created a web api post method to save data. Following is my post method:
[Route("PostRequirementTypeProcessing")]
public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess)
{
mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing();
rTyeProcessing.szDescription = requTypeProcess.szDescription;
rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId;
rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber;
rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer;
rTyeProcessing.szOrganization = requTypeProcess.szOrganization;
rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate;
rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate;
rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy;
rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo;
if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo))
{
}
else
{
UploadFile();
}
rTyeProcessing.szSubject = requTypeProcess.szSubject;
rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId;
rTyeProcessing.iEmpId = requTypeProcess.iEmpId;
NPAEntities context = new NPAEntities();
Log.Debug("PostRequirementTypeProcessing Request traced");
var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId,
requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization,
requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy,
requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId,
requTypeProcess.iEmpId);
return newRTP.ToList();
}
There is a field called 'szAttachedDocumentNo' which is a document that's being saved in the database as well.
After saving all data, I want the physical file of the 'szAttachedDocumentNo' to be saved on the server. So i created a method called "UploadFile" as follows:
[HttpPost]
public void UploadFile()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded file from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
//string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]);
//Directory not exists then create new directory
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// Get the complete file path
var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
}
Before running the project, i debbugged the post method, so when it comes to "UploadFile" line, it takes me to its method.
From the file line, it skipped the remaining lines and went to the last line; what means it didn't see any file.
I am able to save everything to the database, just that i didn't see the physical file in the specified location.
Any help would be much appreciated.
Regards,
Somad
Makes sure the request "content-type": "multipart/form-data" is set
[HttpPost()]
public async Task<IHttpActionResult> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents != null && provider.Contents.Count == 0)
{
return BadRequest("No files provided.");
}
foreach (HttpContent file in provider.Contents)
{
string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
byte[] buffer = await file.ReadAsByteArrayAsync();
using (MemoryStream stream = new MemoryStream(buffer))
{
// save the file whereever you want
}
}
return Ok("files Uploded");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
I'm trying to set the wallpaper to an image on my Windows 10 device:
var fileName = postInf.title + ".jpg";
BitmapImage img = new BitmapImage();
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using (var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read))
{
img.SetSource(pictureStream);
}
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(pictureFile);
}
return success;
The storagefile is created fine, have tried with various images from various folders (e.g. My Pictures, Assets, LocalState); always returns false and wallpaper is not set? I have read/write permissions to pictures library, have tried running in debug and release versions. Apparently others are also having this problem.
Your app can't set wallpapers from any folder. Copy file in ApplicationData.Current.LocalFolder and set wallpaper from there.
My code:
if (list.SelectedIndex != -1)
{
var data = list.SelectedItem as ThumbItem;
StorageFile newFile = await data.File.CopyAsync(ApplicationData.Current.LocalFolder);
await SetWallpaperAsync(newFile);
}
async Task<bool> SetWallpaperAsync(StorageFile fileItem)
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(fileItem);
}
return success;
}
look for this error and tell me your opinion to solve this problem
I was making window phone Application :
its can't save my picked file in a storage file to trim it as media
or I can not relate between open file picker and storage file if anyone have any ideas how to relate between them or have any demos please tell me
I'm not sure I understood your problem. Here is my code for picking a file and write into it in WinRT/Win10 store app.
private async void SaveFileExecute()
{
var fileNameTab = FileName.Split('.');
var extension = fileNameTab[1];
var fileName = fileNameTab[0];
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = fileName
};
savePicker.FileTypeChoices.Add(extension, new List<string> { "." + extension });
var saveFile = await savePicker.PickSaveFileAsync();
if (saveFile != null)
{
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = fileStream.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(SelectedFile.Data);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
}
I use Live SDK 5.6 and I'm trying to download file from OneDrive. Using CreateBackgroundDownloadAsync (innerItem.ID + "/Content"), why is result file null?
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
LiveDownloadOperation operation = await liveConnectClient.CreateBackgroundDownloadAsync(innerItem.id + "/Content");
//LiveDownloadOperationResult downloadResult = await operation.StartAsync();
var downloadResult = await operation.StartAsync();
if (downloadResult.File != null)
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.GetFileAsync("MoneyNote.db");
await downloadResult.File.MoveAndReplaceAsync(downFile);
messagePrint(true);
}
else
{
messagePrint(false);
}
}
}
I think the problem may be, because you are creating background download (not downloading in the background), then you start this download operation, but file needs time to be downloaded. In this case probably easier would be just to download a file like this:
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MoneyNote.db", CreationCollisionOption.ReplaceExisting);
var result = await liveConnectClient.BackgroundDownloadAsync(innerItem.id + "/content", downFile);
messagePrint(true);
}
}