Cannot add flipview image when reading pdf on windows phone 8.1 - c#

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.

Related

Get Thumbnail from mp3 file in c# xaml for windows phone 8.1

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)

Windows Phone 8.1 RT PickSaveFileAndContinue() method creates an empty file

I'm trying to save a file to the Documents folder using PickSaveFileAndContinue() method in WP 8.1 RT. Everything is happening fine except the file which gets saved is empty.
When I get the file returned from the following code in OnActivated() method, it's size is zero.
Anyone?
var database = await FileHelper.GetFileAsync(ApplicationData.Current.LocalFolder, DATABASE_NAME);
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Database File", new List<string>() { ".db" });
savePicker.DefaultFileExtension = ".db";
savePicker.SuggestedFileName = DATABASE_NAME;
savePicker.SuggestedSaveFile = database;
After the location is picked, the following code is executed in App.xaml.cs. I tried doing this inside the same page using a ContinuationManager. But then result is same.
protected async override void OnActivated(IActivatedEventArgs args)
{
byte[] buffer = null;
if(args!=null)
{
if(args.Kind == ActivationKind.PickSaveFileContinuation)
{
var file = ((FileSavePickerContinuationEventArgs)args).File;//This is empty
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
buffer = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(buffer);
}
}
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, buffer);
Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
}
}
base.OnActivated(args);
}
That's expected. PickSaveFileAndContinue doesn't know what the app wants to save. It just provides an empty StorageFile. The app can then write whatever contents it wants to save into the file.

How to clear a file before writing into it

I am using this code to write into my file:
private async void play_Click(object sender, RoutedEventArgs e)
{
String MyScore;
Double previousScore = 0;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder1 = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);
var file1 = await dataFolder1.CreateFileAsync("MyFile.txt", CreationCollisionOption.OpenIfExists);
var file = await dataFolder1.OpenStreamForReadAsync("MyFile.txt");
using (StreamReader streamReader = new StreamReader(file))
{
MyScore = streamReader.ReadToEnd();
}
if (MyScore != null && !MyScore.Equals(""))
{
previousScore = Convert.ToDouble(MyScore);
}
Double CurerentScore = 0;
Double Total = 0;
String scoreText = this.ScoreTB.Text;
CurerentScore = Convert.ToDouble(scoreText);
Total = previousScore - CurerentScore;
using (var s = await file1.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}
}
But before writing into it, I want that my file should get cleared. What should I do?
This is what i have tried so far but the problem is that it writes the file up to the filebytes.length and due to that if the new information to be writed in file is less in terms of length in comparison to the privous length then some garbage value or unnecessay thing comes after the end of the new file
You can use this snippet :
var folder = ApplicationData.Current.LocalFolder;
// You are going to replace the file
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
var content = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
await stream.WriteAsync(content, 0, content.Length);
}
To quote the documentation :
ReplaceExisting : Create the new file or folder with the desired name,
and replaces any file or folder that already exists with that name.
I have clear the file by writing a empty string to it and then i have written what i wanted in my file This solved my issue as nothing was there in the file so whatever i wanted to write to it came up successfully.
Simply use Stream.SetLength like this:
using (var s = await file1.OpenStreamForWriteAsync())
{
// Add this line
s.SetLength(0);
// Then write new bytes. use 's.SetLength(fileBytes.Length)' if needed.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}

how to save MemoryStream to JPEG in Windows 8 c#

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);
}
}

How to edit and save photo in Windows Store App?

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();

Categories

Resources