I have canvas made from bitMap (photo) and my finger drawings in Xamarin Forms. I need to save it to memory device (perfectly it would be photo roll but could be just memory of device). For now (after googling few hours) i have something like this:
saveButt.Clicked += async(sender, args) =>
{
var newSurface = SKSurface.Create(
(int)canvasView.CanvasSize.Width,
(int)canvasView.CanvasSize.Height,
SKImageInfo.PlatformColorType,
SKAlphaType.Premul);
var canvas = newSurface.Canvas;
if (photoBitmap != null)
{
canvas.DrawBitmap(photoBitmap, new SKRect(0, 0, (float) canvasView.Width, (float) canvasView.Height));
}
foreach (SKPath path in completedPaths)
{
canvas.DrawPath(path, paint);
}
foreach (SKPath path in inProgressPaths.Values)
{
canvas.DrawPath(path, paint);
}
canvas.Flush();
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
};
I don't know how i can get access to memory or photo roll to save it.
#Edit
I tried use PCLStorage plugin to save it and for now it don't throw any exceptions or errors but still when i look through all folders i can't find any new folder or file with those names.
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("image.png",
CreationCollisionOption.ReplaceExisting);
using (Stream s = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
pngImage.SaveTo(s);
}
Related
I need to crop and display an image using ImageCropper.MAUI, I can't get the image to show up and I get image not found exception.
https://github.com/jbowmanp1107/ImageCropper.Maui
I have added code where I can get the image path after cropped.
ImageCrop.Success = (imageFile) =>
{
Application.Current.Dispatcher.Dispatch(async () =>
{
imageFile = imageFile.Replace(#"/my_images/Pictures/", "");
var _d = FileSystem.Current.AppDataDirectory;
var pathTemp = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), imageFile);
//"/my_images/Pictures/cropped2795616814194734447.png"
//cropped2795616814194734447.png
//cropped9006441269099458689.png
if (File.Exists(pathTemp))
{
//Check for file exists or not
}
path = pathTemp;
resultImage.Source = ImageSource.FromFile(pathTemp);
await Empty();
});
}
I have also attached the path of image as below in emulator.
Image path in emulator
I want to trim a music file(mp3) in my UWP win 10 app. I try using Naudio but it's not working in my app, so how can i do it ?
Anyone any ideas?
If you want to trim a mp3 file, you can use Windows.Media.Editing namespace, especially MediaClip class.
By default, this class is used for clipping from a video file. But we can also use this class to trim mp3 file by setting MediaEncodingProfile in MediaComposition.RenderToFileAsync method while rendering.
Following is a simple sample:
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
var pickedFile = await openPicker.PickSingleFileAsync();
if (pickedFile != null)
{
//Created encoding profile based on the picked file
var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(pickedFile);
var clip = await MediaClip.CreateFromFileAsync(pickedFile);
// Trim the front and back 25% from the clip
clip.TrimTimeFromStart = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
clip.TrimTimeFromEnd = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
var composition = new MediaComposition();
composition.Clips.Add(clip);
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
savePicker.FileTypeChoices.Add("MP3 files", new List<string>() { ".mp3" });
savePicker.SuggestedFileName = "TrimmedClip.mp3";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
//Save to file using original encoding profile
var result = await composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise, encodingProfile);
if (result != Windows.Media.Transcoding.TranscodeFailureReason.None)
{
System.Diagnostics.Debug.WriteLine("Saving was unsuccessful");
}
else
{
System.Diagnostics.Debug.WriteLine("Trimmed clip saved to file");
}
}
}
So I'm using Syncfusion Controls for UWP XAML, and I'm trying to insert JPEGs into a PDF I'm creating, but PdfImage seems to always return bitmaps. Or at least images with bitmap-like file sizes.
Is there any way to ensure the images being inserted are of JPEG size? The images I'm inputting are JPEGs to begin with.
I'd be fine with bitmaps if I wasn't making PDFs of manga (Japanese comic books), i.e. the size per manga right now ranges from 50-150MB.
It's not a working sample, but here's what I'm using right now.
public async void SaveAsPdf(Stream fs, Manga manga)
{
var m = manga;
var c = m.Content;
if (fs.Length != 0) return;
var pdf = new PdfDocument();
var pages = await GetPages(m);
pdf.PageSettings.SetMargins(0);
pdf.FileStructure.IncrementalUpdate = true;
pdf.EnableMemoryOptimization = true;
pdf.Compression = PdfCompressionLevel.Best;
for (var pi = 0; pi < c.ContentPages; pi++)
{
var section = pdf.Sections.Add();
var mr = section.PageSettings.Margins = new PdfMargins();
mr.All = 0;
var page = section.Pages.Add();
var g = page.Graphics;
page.DefaultLayerIndex = 0;
var pu = pages[pi];
var client = new HttpClient();
var im = await client.GetAsync(pu);
var pdi = PdfImage.FromStream(im.Content.ReadAsStreamAsync().Result);
g.DrawImage(pdi, new PointF(0, 0), g.ClientSize);
await pdf.SaveAsync(fs);
}
await pdf.SaveAsync(fs);
pdf.DocumentInformation.Title = c.ContentName;
pdf.DocumentInformation.Author += string.Join(", ", c.ContentArtists.Select(x => x.Attribute));
pdf.DocumentInformation.Keywords += string.Join(", ", c.ContentTags.Select(x => x.Attribute)).Replace("\"", string.Empty);
pdf.Save(fs);
pdf.Close(true);
var toast = Notifications.NotifyMangaDownloaded(m);
ToastNotificationManager.CreateToastNotifier().Show(toast);
fs.Dispose();
}
I'd ask about the memory leak but it'd probably be best if I made another post for that.
Thanks in advance.
(I posted this on the Syncfusion forums but I felt like I might get a better response here)
Well, I refactored some of the methods and the memory leak ended up being the cause. Lesson learned: using statements are your friends.
To be a little more specific, I just created a file as a destination for the PDF, then called
using (Stream s = new FileStream(/*string*/>f.Path, FileMode.OpenOrCreate))
{
await Task.Run(() => SaveAsPdf(/*StorageFile*/f, /*Manga*/m));
}
Various other things needed to be moved around, but leaving the FileStream open ended up being the problem.
I am developing this application where I am able to get all the pictures from picture library as StorageFile data type. now I want to change it to writeablebitmap, apply a sketch filter and show in image control. can someone please help me in changing the data type from StorageFile to writeablebitmap?
here is my code:
StorageFolderpicturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageFile> file = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(file.Count > 0)
{
foreach(StorageFile f in file)
{
// the code for changing the data type will go here
}
This code works for me.
if (file.Count > 0)
{
foreach (StorageFile f in file)
{
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
WriteableBitmap bmp = new WriteableBitmap((int)properties.Width, (int)properties.Height);
bmp.SetSource((await f.OpenReadAsync()).AsStream());
// Ready to go with bmp
}
}
Try this, it should work:
IReadOnlyList<IStorageFile> files = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(files.Count > 0)
{
var images = new List<WriteableBitmap>();
foreach(var f in files)
{
var bitmap = new WriteableBitmap(500, 500);
using (var stream = await f.OpenAsync(FileAccessMode.ReadWrite))
{
bitmap.SetSource(stream);
}
images.Add(bitmap);
}
}
I am developing project in C# windows application. I am new to this technology. I declared Image variable in one class and list in another class. I want to retrieve image from Resource folder and store it in list ten times. I wrote code like this but it is returning null.
class clsAddImage
{
public Image m_imgSampleImage;
}
class clsList
{
public List<clsAddImage> lstImage = new List<clsAddImage>();
}
class clsAddImageToList
{
public void AddImgMethod()
{
clsList objlist = new clsList();
int i;
for (i = 0; i < 10; i++)
{
clsAddImage objaddimg = new clsAddImage();
objlist.lstImage.Add(objaddimg);
}
foreach (clsAddImage addimg in objlist.lstImage)
{
string path = "C:\\Users\\c09684\\Documents\\Visual Studio 2010\\Projects\\WindowsFormsAddImage\\WindowsFormsAddImage\\Resources\\Chrysanthemum.jpg";
addimg.m_imgSampleImage = Image.FromFile(path);
}
}
}
public Form1()
{
InitializeComponent();
clsAddImageToList a = new clsAddImageToList();
a.AddImgMethod();
}
I assume that you refer to a Windows8 app? In that case you can not simply program a directory to retrieve information. The user has to choose a directory manually, which you can store for future use. However, you can have access to KnownFolders (for most you have to check Capabilities in the Package.appxmanifest, e.g. Pictures Library), see http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.knownfolders for the options.
With the following task you will be able to retrieve files from a directory, I hope this helps you solving your problem:
public async Task GetFilesFromDisk()
{
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StringBuilder outputText = new StringBuilder();
IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
var images = new List<BitmapImage>();
if (fileList != null)
{
foreach (StorageFile file in fileList)
{
string cExt = file.FileType;
if (cExt.ToUpper() == ".JPG")
{
Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
using (Windows.Storage.Streams.IRandomAccessStream filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
}
}
} // ForEach
}
}