Displaying PNG Image from Isolated Storage - c#

I've been working for a few days trying to figure out how to save and load images to and from isolated storage. Yesterday, I finally managed to fix whatever issue I was having with storing them, but now I need to add the image as the icon to a menu item, and I don't know what is wrong with my code:
var image = new System.Windows.Controls.Image();
using(var stream = new IsolatedStorageFileStream((string) (directory + file + ext),
FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
{
image.Source = (BitmapSource) new PngBitmapDecoder(stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOptions.Default).Frames[0];
}
Menu menu = new Menu();
MenuItem item = new MenuItem();
item.Header = file;
item.Icon = image;
menu.Items.Add(item);
The image comes up in the menu as the right size, but it's a blank image. The image file shows the image just fine when I preview it in Windows Photo Viewer.
I'm still pretty new to C# and WPF (only been working with it for 3 months), and I'm looking for a simple solution that doesn't really need to be elegant or generic; it just needs to work.

It figures that I would answer my own question half an hour after asking for help. Scoured the Web for days trying to figure it out, and it just falls in my lap. I just needed to instantiate my stream with the correct FileAccess:
I just replaced
using(var stream = new IsolatedStorageFileStream((string) (directory + file + ext),
FileMode.Open, IsolatedStorageFile.GetUserStoreForAssembly()))
with
using(var stream = IsolatedStorageFile.GetUserStoreForAssembly().OpenFile(
(string) (directory + file + ext), FileMode.Open, FileAccess.Read))

Related

How to change default image folder on Xamarin forms (android)

I am having the issue of "Canvas Drawing too large bitmaps". After a quick search, I found the following thread, which promptly helped me know what is the issue.
The solution is to put the image in drawable-xxhdpi/ instead of simply drawable/. And here lies the issue: the image is not static, it is imported when I need it. As such, I do not chose where the image ends up stored. It store itself in drawable. Is there 1) A solution to chose which folder to use, or 2) a way to tell it not get the image if it's too heavy?
var file = new SmbFile(path, auth);
try
{
if (file.Exists())
{
// Get readable stream.
var readStream = file.GetInputStream();
//Create reading buffer.
MemoryStream memStream = new MemoryStream();
//Get bytes.
((Stream)readStream).CopyTo(memStream);
var stream1 = new MemoryStream(memStream.ToArray());
if (stream1.Length < 120188100)
{
//Save image
ProductImage = ImageSource.FromStream(() => stream1);
//Dispose readable stream.
readStream.Dispose();
InfoColSpan = 1;
}
else
{
Common.AlertError("Image trop lourde pour l'affichage");
}
}
}

C# How to create in-memory video chunks

I need to record screen and on event like button click it should save last 60 seconds of recording.
I know how to capture screenshots but I have problems with converting the images to the video. I want to save the final video file and everything else should be in memory operations.
Currently I save captures as JPEG to memory stream and when the event is fired then I convert the images to the video files. But there is tripple conversion: Bitmap[] -> JPEG[] -> Bitmap[] -> Video. That seems ineffective.
When I googled I found only how to save video file to file system. For example Accord library have VideoFileWritter (example for version 3.8.2 alpha)
Bitmap bitmap; //bitmap object with screenshot
List<byte[]> data = new List<byte[]>();
// fill data with JPEG images (called periodically)
using (var ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data.Add(ms.GetBuffer());
}
// create video file (called on demand)
using (VideoFileWriter videoWriter = new VideoFileWriter())
{
videoWriter.BitRate = videoBitRate;
videoWriter.FrameRate = Settings.CurrentFramesPerSeconds;
videoWriter.Width = 1920;
videoWriter.Height = 1080;
videoWriter.VideoCodec = VideoCodec.H264;
videoWriter.VideoOptions["crf"] = "18"; // visually lossless
videoWriter.VideoOptions["preset"] = "veryfast";
videoWriter.VideoOptions["tune"] = "zerolatency";
videoWriter.VideoOptions["x264opts"] = "no-mbtree:sliced-threads:sync-lookahead=0";
videoWriter.Open(Path.Combine(dirName, "output.avi"));
foreach (var frame in data)
{
using (var bmpStream = new MemoryStream(frame))
using (var img = Image.FromStream(bmpStream))
using (var bmp = new Bitmap(img))
videoWriter.WriteVideoFrame(bmp);
}
}
How to create video chunks in memory? I guess it should be CPU and memory more efficient than my current solution.
Or is there more efficient way to record last few seconds of screen without file system usage?
I don't want to use file system because only ssd is installed in computer.

Google drive upload an image from memory stream

Good day,
I have this code which upload an image to Google drive from file, everything works well:
// Create a new file on Google Drive
using (var fsSource = new FileStream(UploadFileName, FileMode.Open, FileAccess.Read))
{
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "image/jpg");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);
}
Now I want to do some image manipulation before uploading so that I could convert the image to jpeg if the image is in another format (png or bmp for example) or resize the image, so I changed the file to stream for manipulation, I don't want to save it locally again because the code could be used on a website on mobiles, that's why I am saving to stream.
using (MemoryStream ms = new MemoryStream())
{
Image img = Image.FromFile(uploadfileName);
img.Save(ms, ImageFormat.Jpeg);
}
How can I now upload this ms stream to Google Drive?
Thanks for any clue, I'm not an expect in field.
Thanks all for assistance.
The answer suggested by canton7 works:
Just set ms.Position = 0, so that the next read starts reading from the beginning of the stream, then use it in place of your fsSource in your first snippet

Saving bitmap from clipboard into png in wpf application

i needed to send bitmap into my chat application soo my idea was save it into a temporaty folder and from there upload it like my drag and drop image thats already working. but when it saves the bitmap in windows fileviewer i can see thumbnail but everywhere else its empty any idea where the problem could be or how to do this any better way? thanks in advance.
here is a video so you can better understand ^^ https://youtu.be/p0t2byTRN58
string temp = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName + #"\Luxray\" + #"\clipboardimg.png";
if (File.Exists(temp))
{
File.Delete(temp);
}
BitmapSource bmpSource = Clipboard.GetImage();
MemoryStream ms = new MemoryStream();
FileStream stream = new FileStream(temp, FileMode.Create);
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpSource));
encoder.Save(stream);
stream.Close();
this code runs right after if statment that checks if clipboard has bitmap inside and ctrl+v was pressed in the video it is after msgbox with "img sent" pops up.
What are you trying to achieve? if you're trying to save a clipboard image to file the below code works for me:
var img = System.Windows.Forms.Clipboard.GetImage();
img.Save(savePath, ImageFormat.Png);

How do I fill a rectangle with an ImageBrush using a file from the hard drive

I am trying to fill a rectangle with a file that I have saved to the hard drive. I know that I have to use a ImageBrush and I think I know how to do that if the image is an included resource. In this case the file is created and setting on the hard drive but when I try to use it with the code below the rectangle changes but it changes to show the form back color not the image as I had expected (almost as if the image is invisible).
using (dynamic CommonDialog = AutomationFactory.CreateObject("WIA.CommonDialog"))
{
dynamic imageFile = CommonDialog.ShowAcquireImage();
if (imageFile != null)
{
string filePath = string.Format("d:\\{0}.jpg", Guid.NewGuid());
imageFile.SaveFile(filePath);
rectangle2.Fill = new ImageBrush()
{
ImageSource = new BitmapImage(new Uri(filePath, UriKind.Absolute))
};
}
}
Update: I was able to get this to work by replacing the code block inside the If Then with the following:
{
string filePath = string.Format("d:\\{0}.jpg", Guid.NewGuid());
imageFile.SaveFile(filePath);
BitmapImage bitmapBase = new BitmapImage();
dynamic fileData = imageFile.FileData;
byte[] imageData = fileData.BinaryData;
MemoryStream ms = new MemoryStream(imageData);
bitmapBase.SetSource(ms);
WriteableBitmap writableBitmap = new WriteableBitmap(bitmapBase);
rectangle2.Fill = new ImageBrush() { ImageSource = (writableBitmap) };
}
When using Silverlight 4 you can create an out-of-browser application thatt can access (part of) the local disk.
See here how
You cannot access images, or any files, from a local drive (except for Isolated storage or a stream from a file open dialog). These are all security measures.
As you did not mention Out Of Browser I assume this is just a web/client app.

Categories

Resources