I am trying to change the Background of a button to an image source. I want to load that image in memory when we navigate to the page so that it doesn't flicker the first time it shows.
On Windows Phone, I was able to create the image source as such:
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage bitmapSource = new BitmapImage();
// Avoid flicker by not delay-loading.
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.SetSource(resourceInfo.Stream);
imageSource = bitmapSource;
I tried something similar in my Windows 8 Store app:
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.CreateOptions = BitmapCreateOptions.None;
bitmapSource.UriSource = uri;
imageSource = bitmapSource;
but the same problem occurs. The button already has a different image as the Background, and on a certain event I would like it to change to the new background. But when I change the source, a noticeable flicker is observed. I'm assuming this is because the image is not yet in memory, as the issue goes away the second time the image source is modified.
Anyone know a solution? I need to somehow force the loading of this image.
Thanks!
If you use the SetSourceAsync method on the BitmapImage and await it before you attach it to the image source you should not see the flicker:-
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
imageSource = bitmapImage;
}
The MSDN docs have some more info on this
Thanks Ross, but what I ended up doing instead is I preloaded the half dozen or so bitmaps I needed by using similar code to what you had above, except from resource of course. I did this asynchronously when the page loaded, and then when I set the ImageSource on the button background, I used the already preloaded bitmaps. That way I know I'm not allocated a new chunk of memory for every instance of the bitmap.
Related
I am using DotNetBrowser Control in my c# desktop application. I am not able to get captcha image using this.
It is easy in Webbrowser control but in DotNetBrowser I don't know how to do so in c#
https://dotnetbrowser.support.teamdev.com/support/solutions/9000111998
This code is working if I am using Webbrowser control
private Image getCaptcha()
{
HtmlElement ement = webBrowser1.Document.GetElementById("imgCaptcha");
if (ement == null)
{
return null;
}
mshtml.HTMLWindow2 w2 = (mshtml.HTMLWindow2)webBrowser1.Document.Window.DomWindow;
w2.execScript("var ctrlRange = document.body.createControlRange();
ctrlRange.add(document.getElementById('imgCaptcha'));
ctrlRange.execCommand('Copy');", "javascript");
return Clipboard.GetImage();
}
I need similar code in DotNetBrowser control
You can use the 'Browser.ImageProvider.GetImage' method to get the screenshot of the page and then crop this image to the bounds of the captcha image.
The only restriction is that the Browser should use the lightweight rendering mode as getting an image is unavailable in the heavyweight mode.
The described approach may look like the following source code:
browserView = new WinFormsBrowserView(BrowserFactory.Create(BrowserType.LIGHTWEIGHT));
//...
browserView.Browser.SetSize(1024, 768);
Bitmap screenshot = browserView.Browser.ImageProvider.GetImage() as Bitmap;
DOMElement captchaElement = browserView.Browser.GetDocument().GetElementById("imgCaptcha");
pictureBox1.Image = screenshot?.Clone(captchaElement.BoundingClientRect, screenshot.PixelFormat);
I have an Image in a grid where I display some custom content by setting the Image's source to a WritableBitmap and updating the bitmap. What I want to do is to implement a "detach" button that will put my Image on a separate window allowing the user to move it to a different screen, resize it etc. independent of my main app window. If the new window is closed, I would like to bring it back to its original spot. While the Image is on the new window, I want to continuously update it with new content via updating source bitmap (as it would have been before it was detached).
I initially thought I would be able to create a new window and "move" my Image control there by first removing it from its original parent then adding it as a child to a layout in the new window. I used the code below:
CoreApplicationView^ newCoreView = CoreApplication::CreateNewView();
int mainViewId = Windows::UI::ViewManagement::ApplicationView::GetApplicationViewIdForWindow(
CoreApplication::MainView->CoreWindow);
uint indexOfObjectToDetach = -1;
bool found = originalGrid->Children->IndexOf(imageToMove, &indexOfObjectToDetach);
if(found)
{
myGrid->Children->RemoveAt(indexOfObjectToDetach);
}
DispatchedHandler^ dispatchHandler = ref new DispatchedHandler([this, mainViewId]()
{
newView_ = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView();
Windows::UI::Xaml::Controls::StackPanel^ newWindowGrid = ref new Windows::UI::Xaml::Controls::StackPanel();
Window::Current->Content = newWindowGrid;
Window::Current->Activate();
newWindowGrid->Children->Append(imageToMove); // Add to new parent
});
create_task(newCoreView->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, dispatchHandler)).then([this, mainViewId]()
{
auto a = newView_->Id;
create_task(ApplicationViewSwitcher::TryShowAsStandaloneAsync(a, ViewSizePreference::Default, mainViewId, ViewSizePreference::Default));
});
However in the line where I add the Image to its new parent, I get an Interface was marshalled for a different thread error. Upon more reading, this is due to the fact that each new window is in its own thread and I'm moving an object to another thread.
I am new to UWP and I am not sure how to approach implementing this UI behavior. How do I access/transfer my state in one view to another ?
The problem is indeed the fact that each application view in UWP has its own thread and its own UI dispatcher. When you create a control, it is tied to the UI thread it was created on, hence you cannot place it onto another application view.
The solution is to create the new Image next to the StackPanel within the new view's UI thread. I don't really use C++, but in C# I would implement it as follows:
await newCoreView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
StackPanel panel = new StackPanel();
Image image = new Image();
panel.Children.Add( panel );
image.Source = ...; //your source
Window.Current.Content = frame;
Window.Current.Activate();
newViewId = ApplicationView.GetForCurrentView().Id;
});
To further clarify - you can safely "transfer" normal data types into other view, the problem is mainly with the UI-tied types like controls, pages, etc.
I have a database program that stores images to the SQL DB and reads them back to be displayed in a WPF application. if i use Jpeg images it works fine, but if i use PNG images, which i wanted to use to try and keep the transparency ( which disappears anyway when stored ) most of the images come back corrupt.
this is the image that has been selected
i then save it to the db, and add the image the listview
then if i close the application and reload it, it pulls the image back from the db, you can see that it is corrupt in the listview
and then when i select it, the image control also shows the corrupted image
i am storing the image in code using a BitmapImage object, and use this to set the image.source, and also convert this to a byte[] for storing into the image field in the database.
i convert the bitmapimage to a Byte[] with the following line
command.Parameters.AddWithValue("#Image", ImageToByteArray(productImage.ProductImage));
and these are the functions to convert to and from a bitmapimage
private static BitmapImage BuildImage(byte[] image)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
MemoryStream mem = new MemoryStream(image);
bitmap.StreamSource = mem;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
//bitmap.Freeze();
return bitmap;
}
private static byte[] ImageToByteArray(BitmapImage image)
{
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
works fine with Jpegs, but then i have the white background to the images.
any help would be much appreciated.
"JpegBitmapEncoder" is a large clue. Surely you'd want "PNGBitmapEncoder"...?
As personal preference I would change your SQL data column to varbinary(MAX) and use stream and BinaryReader objects to upload the file.
However I think your issue is you are not using PngBitmapEncoder for the PNG you are using the JpegBitmapEncoder irrespective of filetype.
Hope this helps.
I am new to Windows 8 app development. In my app I need to display a GridView with images and title. The image URL and the title I get from the server as a XML data. The images are downloaded from the given URL and stored in a local directory. Now, when an image is downloaded I want to notify the GridView and update the particular image view with the downloaded image. I store the title and the local image URI in an ObservableCollection. The data source of the GridView is bound to this ObservableCollection, so once the XML data is downloaded I am able to update the title through the ObservableCollection. But i don't know how to update the images once they are downloaded.
Assuming that your image is saved in the local data folder (ApplicationData.Current.LocalFolder) - you can create a new BitmapImage this way:
var imagePathInLocalDataFolder = ?
var imageUri = new Uri("ms-appdata:///local/" + imagePathInLocalDataFolder, UriKind.Absolute);
var bitmapImage = new BitmapImage(new Uri(imageUri));
You can then assign the bitmapImage variable value to a property that you bind to an Image.Source - and you should see your image.
I'm building a Win8/WinJS app that loads pictures from the local pictures library. Everything is generally working fine for loading valid images and displaying them in a list view.
Now I need to detect corrupt images and disable parts of the app for those images.
For example, open a text file and enter some text in it. Save the file as .jpg, which is obviously not going to be a valid jpg image. My app still loads the file because of the .jpg name, but now I need to disable certain parts of the app because the image is corrupt.
Is there a way I can check to see if a given image that I've loaded is a valid image file? To check if it's corrupt or not?
I'm using standard WinRT / WinJS objects like StorageFile, Windows.Storage.Search related objects, etc, to load up my image list based on searches for file types.
I don't need to filter out corrupt images from the search results. I just need to be able to tell if an image is corrupt after someone selects it in a ListView.
One possible solution would be to check the image's width and height properties to determine whether it is valid or not.
Yeah, the contentType property will return whatever the file extension is. The best way I can find it to look at the image properties:
file.properties.getImagePropertiesAsync()
.done(function(imageProps) {
if(imageProps.width === 0 && imageProps.height === 0) {
// I'm probably? likely? invalid.
});
where SelectImagePlaceholder is an Image Control.. =)
StorageFile file;
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
SelectImagePlaceholder.Source = bitmapImage;
//SelectImagePlaceholder.HorizontalAlignment = HorizontalAlignment.Center;
//SelectImagePlaceholder.Stretch = Stretch.None;
this.SelectImagePlaceholder.DataContext = file;
_curMedia = file;
}
catch (Exception ex)
{
//code Handle the corrupted or invalid image
}
}