I make some application which edit photo and save it in other location. So I find a question which shows how to resize photos in Windows Store Apps. Then I implement it in my program:
private async void ResizeButton_Click(object sender, RoutedEventArgs e)
{
uint width, height;
if (uint.TryParse(WidthTextBox.Text, out width) && uint.TryParse(HeightTextBox.Text, out height)
&& _folderWithPhoto != null && _targetFolder != null)
//_folderWithPhoto and _targetFolder are StorageFolder values get from FolderPicker
{
var files = await _folderWithPhoto.GetFilesAsync();
foreach (StorageFile item in files)
{
if (item.ContentType.Contains("image"))
{
StorageFile targetFile = await item.CopyAsync(_targetFolder, item.Name, NameCollisionOption.GenerateUniqueName);
var fileStream = await targetFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);
enc.BitmapTransform.ScaledHeight = height;
enc.BitmapTransform.ScaledWidth = width;
await enc.FlushAsync();
}
}
}
}
Problem
Result of this code is the same photo saved in _targetFolder catalogue. So I have no idea how to fix it.
Any help would be appreciated.
Mateusz will something like this inside your foreach loop work I am not sure
ras.Seek(0);
fileStream.Seek(0);
fileStream.Size = 0;
await RandomAccessStream.CopyAsync(ras, fileStream);
fileStream.Dispose();
ras.Dispose();
Related
i need to save the picture getting from the camera in a specific folder but i can't find the way, i онли show it in the xaml.
class CameraOpening{
public async Task<SoftwareBitmapSource> PhotoTake(){
var captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.AllowCropping = false;
var photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
var bitmapSource = new SoftwareBitmapSource();
if (photo != null){
var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(
"ProfilePhotoFolder", CreationCollisionOption.OpenIfExists);
await photo.CopyAsync(folder,"ProfilePhoto.jpg",NameCollisionOption.ReplaceExisting);
using (var stream = await photo.OpenAsync(FileAccessMode.Read)){
var decoder = await BitmapDecoder.CreateAsync(stream);
var softwareBitmap = await decoder.GetSoftwareBitmapAsync();
var softwareBitmapBGR8 = SoftwareBitmap.Convert(
softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);}
await photo.DeleteAsync();}
return bitmapSource;}}
public async void Buttonfoto(object sender, RoutedEventArgs e)
{
var cam = new CameraOpening();
imageControl.Source = await cam.PhotoTake();
}
and the xaml has the Image and the Button
there is a way for save the picture taken in a specific directory?
or a copy of it.
Lines:
var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder", CreationCollisionOption.OpenIfExists);
await photo.CopyAsync(folder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
already seems to be saving your photo to path ./ProfilePhotoFolder/ProfilePhoto.jpg.
But it will save only if picture was actually taken.
var photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
// < ... >
if (photo != null) { /* save file! */ }
Check what captureUI.CaptureFileAsync actually returns.
If it's null - nothing will happen.
But if your photo is being taken and already saving itself to ./ProfilePhotoFolder/ProfilePhoto.jpg you can save it again via:
await photo.CopyAsync(folder, "C:\\SomeFolder\\MyPhoto.jpg", NameCollisionOption.ReplaceExisting);
Or copy already created picture via:
File.Copy(".\\ProfilePhotoFolder\\ProfilePhoto.jpg", "C:\\SomeFolder\\MyPhoto.jpg");
More info here:
System.IO and System.IO.File
I made an application on windows phone 8.1 for reading pdf using xfinium. I have problems when adding flipview upon reading the pdf.
Image is not displayed and display an error message such as this link
Code:
async private void LoadFile(string name)
{
StorageFolder installedLocation = ApplicationData.Current.LocalFolder;
StorageFolder koleksibuku = await installedLocation.CreateFolderAsync("koleksibuku", CreationCollisionOption.OpenIfExists);
IReadOnlyList<StorageFile> files = await koleksibuku.GetFilesAsync();
StorageFolder thumbfolder = await installedLocation.CreateFolderAsync("thumb", CreationCollisionOption.OpenIfExists);
foreach (StorageFile file in files)
{
if (file.DisplayName == name)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
Stream fileStream = stream.AsStreamForRead();
PdfFixedDocument document = new PdfFixedDocument(fileStream);
//fileStream.Dispose();
(Application.Current as App).Document = document;
int i = 0;
for (i = 0; i < document.Pages.Count; i++)
{
int index = i;
var t = Task<PdfBgraByteRenderingSurface>.Factory.StartNew(() =>
{
PdfPageRenderer renderer = new PdfPageRenderer(document.Pages[index]);
PdfBgraByteRenderingSurface rs = renderer.CreateRenderingSurface<PdfBgraByteRenderingSurface>(96, 96);
PdfRendererSettings settings = new PdfRendererSettings(thumbnailDpi, thumbnailDpi, rs);
renderer.ConvertPageToImage(settings);
return rs;
})
.ContinueWith(value =>
{
PdfBgraByteRenderingSurface rs = value.Result;
WriteableBitmap pageBitmap = new WriteableBitmap(rs.Width, rs.Height);
Stream imageStream = pageBitmap.PixelBuffer.AsStream();
imageStream.Write(rs.Bitmap, 0, rs.Bitmap.Length);
flipView.SelectionChanged += flipView_SelectionChanged;
flipView.Loaded += flipView_Loaded;
flipView.ItemsSource = pageBitmap;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}
}
How to handle it?
My recommendation is to check the Length of the imageStream and its Position. The Position should be 0 and the imageStream.Length should be equal to rs.Bitmap.Length. If they are different please send a sample project to XFINIUM.PDF support.
Disclaimer: I work for the company that develops XFINIUM.PDF library.
Is there a way I can get the image as Stream and then store it locally to upload it to server?
So far I found the code below which lets me load the image to an image view , but how do I create a stream from the image source to pass it to SaveToLocalFolderAsync method?
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
imgCover.Source = bitmapImage;
//save the image in local folder
//SaveToLocalFolderAsync(stream, "Test.jpg");
}
}
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}
I need to get Thumbnail from mp3 files. I Implemented this but it never catch thumbnails. I checked the existence of the images opening them with windows media player and from xbox music (on the phone) but i can't retrieve them in my app. Please Help
async private void ThumbnailFetcher(StorageFile file)
{
if (file != null)
{
const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;
const uint size = 100;
using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size))
{
if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
{
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
BitmapImage thumbnailImage = new BitmapImage();//image used for display
thumbnailImage.SetSource(thumbnail);
CurrentAlbumArt.Source = thumbnailImage;
Debug.WriteLine("true");
});
}
else
{
Debug.WriteLine("False");
}
}
}
}
P.s It gives always false.
It seems there is a bug on windows phone 8.1, I searched all the night and the only method I could implemented is this
var fileStream = await file.OpenStreamForReadAsync();
var TagFile = File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
// Load you image data in MemoryStream
var tags = TagFile.GetTag(TagTypes.Id3v2);
IPicture pic = TagFile.Tag.Pictures[0];
MemoryStream ms = new MemoryStream(pic.Data.Data);
ms.Seek(0, SeekOrigin.Begin);
bitmap.SetSource(ms.AsRandomAccessStream());
AlbumArt.Source = bitmap;
but it doesn't work too..
var filestream = await receivedFile.OpenStreamForReadAsync();
var tagFile = File.Create(new StreamFileAbstraction(receivedFile.Name, filestream, filestream));
var tags = tagFile.GetTag(TagLib.TagTypes.Id3v2);
var bin = (byte[])(tags.Pictures[0].Data.Data);
MemoryStream ms = new MemoryStream(bin);
await bitmapImage.SetSourceAsync(ms.AsRandomAccessStream());
AlbumArt.Source=bitmapImage;
use this and taglib portable. (Sorry for take so much time)
I see solution for this problem:
Saving as jpeg from memorystream in c#
but it does not work in winRT.
Is there a simple way to save MemoryStream as JPEG using FileSavePicker?
I tried:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
Stream x = await file.OpenStreamForWriteAsync();
image.WriteTo(x)
}
but it is saving blank file. May be I am doing something wrong.
Tried one more approach but again blank image:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
int end = (int)image.Length;
byte[] buffer = new byte[end];
await image.ReadAsync(buffer, 0, end);
await FileIO.WriteBytesAsync(file, buffer);
}
Got it! It was the seeking position I was missing and also the "using". Had to set it externally to 0.
Here is the code:
private async void Save_Image(MemoryStream image)
{
// Launch file picker
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file == null)
return;
using (Stream x = await file.OpenStreamForWriteAsync())
{
x.Seek(0, SeekOrigin.Begin);
image.WriteTo(x);
}
}