How to get thumbnails from a file - c#

I have build a winform application which connects a technical drawing application (CAD - SolidEdge) and an ERP-system. This is working fine but I can't get the right thumbnails in the bomstructure.
When I click on a file in Windows (Windows 10) I see a nice preview image. How can I extract this image to my application?
I had found a similar question and solution (Extract thumbnail for any file in Windows) but this is won't work anymore (because of Windows 10 updates I guess).
Also this one (C# get thumbnail from file via windows api) doesn't work and gives: Example wrong thumbnail and Example wrong thumbnail.
Have you guys any idea how to solve this? Thanks!!

There are different types of thumbnails that can be retrieved from Windows.
Picture
Song Album Art
Document Icon
Folder
File Group
Single Item
Microsoft has a nice sample project called FileThumbnails that lets you play with each type. This project was updated for Windows10 and VS 2019 in March 2020. Although it's a universal windows project instead of winforms.
After playing with the different modes I found the one you are after for Solid Edge files is #6.
internal class FileExtensions
{
public static readonly string[] SEfiles = new string[] { ".dft", ".par", ".asm" };
}
FileOpenPicker openPicker = new FileOpenPicker();
foreach (string extension in FileExtensions.SEfiles)
{
openPicker.FileTypeFilter.Add(extension);
}
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
const ThumbnailMode thumbnailMode = ThumbnailMode.SingleItem;
bool fastThumbnail = FastThumbnailCheckBox.IsChecked.Value;
ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
if (fastThumbnail)
{
thumbnailOptions |= ThumbnailOptions.ReturnOnlyIfCached;
}
using (StorageItemThumbnail thumbnail = await file.GetScaledImageAsThumbnailAsync(thumbnailMode, size, thumbnailOptions))
{
if (thumbnail != null)
{
MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailMode.ToString(), size, file, thumbnail, false);
}
else
{
rootPage.NotifyUser(Errors.NoThumbnail, NotifyType.StatusMessage);
}
}
}
public static void DisplayResult(Image image, TextBlock textBlock, string thumbnailModeName, uint size, IStorageItem item, StorageItemThumbnail thumbnail, bool isGroup)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(thumbnail);
image.Source = bitmapImage;
textBlock.Text = String.Format("ThumbnailMode.{0}\n"
+ "{1} used: {2}\n"
+ "Requested size: {3}\n"
+ "Returned size: {4}x{5}",
thumbnailModeName,
isGroup ? "Group" : item.IsOfType(StorageItemTypes.File) ? "File" : "Folder",
item.Name,
size,
thumbnail.OriginalWidth,
thumbnail.OriginalHeight);
}
Result Example:

Related

How to create a button which takes a picture

I'm writing a cross-platform (iOS and Android) app in C# using Xamarin on Visual Studio Community 2022. I have implemented a camera preview on the app using the code found at this website :
https://www.c-sharpcorner.com/article/creating-a-custom-camera-view-basic-concept-create-half-screen-camera-in-xamari/
The code on the website is for iOS, but there is a link at the bottom to download a folder which contains the code for Android as well. My app now displays a camera preview, but there is no way to take a picture with this. I therefore want to create a button which takes a picture without having to open the camera app. I'd also like the resulting photo to not be saved in the photos of the phone. I have looked but have found no way of doing exactly what I want, and therefore I don't know where to get started. If the answer could give as many details as possible about how to do this for both platforms it would be appreciated. Also, would the resulting photo be of the type FileResult? I have previously worked with the mediapicker in Xamarin which returns the type FileResult, but have come to realize that there are limitations within the mediapicker and I therefore can't work with it.
Thanks a lot :)
You can try MediaPicker to capture picture.And get the filepath in photo.FullPath.
You can refer to the link below to get more details:
https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=ios
edit:
private void cameraView_MediaCaptured(object sender, Xamarin.CommunityToolkit.UI.Views.MediaCapturedEventArgs e)
{
byte[] image = e.ImageData;
DependencyService.Get<ISaveService>().wirteFile("pic.jpg", image);
}
public interface ISaveService
{
void SaveFile(string fileName, byte[] data);
}
Android:
[assembly: Xamarin.Forms.Dependency(typeof(SaveService))]
namespace cameraviewDemo.Droid
{
public class SaveService: ISaveService
{
void ISaveService.SaveFile(string fileName, byte[] data)
{
string picPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryPictures);
string filePath = Path.Combine(picPath, fileName);
File.WriteAllBytes(filePath, data);
}
}
}
iOS:
[assembly: Xamarin.Forms.Dependency(typeof(SaveService))]
namespace cameraviewDemo.iOS
{
class SaveService: ISaveService
{
void ISaveService.SaveFile(string fileName, byte[] data)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, fileName);
File.WriteAllBytes(filename, data);
}
}
}

Xamarin Media Plugin Crashes when second photo is taken

I am using the Plugin.Media (jamesmontemagno/MediaPlugin) plugin for Xamarin and I am having an issue with accepting a picture. When I take the second picture (the first picture works fine) and I click to accept the image the whole app crashes with no output as to the error. I have tried trapping the error but cannot find where it is occurring. I have as suggested removing the min SDK from Android manifest, but the crash still happens.
I have tried looking through the output in visual studio but it is always different. I am assuming the code works as it takes the image and gives me data back, to be clear, it only happens when trying to accept the second image.
private string GetTimestamp(DateTime value)
{
string timestamp = value.ToString("yyyyMMddHHmmssfff");
string filename = timestamp + ".jpg";
return filename;
}
public Command CaptureImage => new Command(TakePicture);
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
//Some message
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "FoodSnap",
Name = GetTimestamp(DateTime.Now) //Gets a unique file name,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom,
CustomPhotoSize = 50
});
if (file == null)
return;
FilePath = file.Path;
}
I am completely stumped as to why this is happening. I am also having trouble refreshing my ViewModel when data changes in the page I am using to take the image. I can't help wondering if this has something to do with it.
I solved the problem by testing each line of code. Once I removed PhotoSize = Plugin.Media.Abstractions.PhotoSize.Custom I could take as many pictures as I need. I did use the Github information for the plugin.
I would be interested to know what I did wrong to cause the error. I would suggest that I have misunderstood the tutorial on Github.

Search image by textbox

I seek for solution which I need to search image at textbox.
When value in TextBox same with image name, the picturebox will display that image. Because I have many picture in 1 folder. Can anyone help me pleaseee? Here is my current code:
if (textBoxEmplNo.Text == "TR0319")
{
pictureBox1.Image = Image.FromFile(#"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\tr0319.jpg");
}
Are you looking for something like this?
string imgFilePath = #"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg"
if(File.Exists(imgFilePath))
{
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
}
Here's a variation that has a couple of advantages thay may or may not be beneficial to you:
var folderPath = #"C:\Users\may\Documents\Visual Studio 2013\WebSites\EV\photo";
var filePaths = Directory.GetFiles(folderPath);
var filePath = filePaths.FirstOrDefault(s => Path.GetFileNameWithoutExtension(s).Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase));
if (filePath != null)
{
pictureBox1.ImageLocation = filePath;
}
That allows your image files to have any extension and it also won't lock the file when it opens one.

Open custom files with own C# application

I'm creating a media player.
So far I can open a file type with my C# application by double clicking on the file. But I want to open multiple files by selecting them and opening them at once..
My code goes as follows:
App.xmal.cs
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args != null && e.Args.Length > 0)
{
this.Properties["ArbitraryArgName"] = e.Args[0];
}
base.OnStartup(e);
}
MainWindow.xmal.cs
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
if (fname.EndsWith(".mp3") || fname.EndsWith(".wma") || fname.EndsWith(".wav") || fname.EndsWith(".mpg") ||
fname.EndsWith(".mpeg") || fname.EndsWith(".mp4") || fname.EndsWith(".wmv") )
{
doubleclicktrack(fname);
}
else
{
this.Close();
}
}
This code works fine with one file, but how to change this in order to open multiple files at once by selecting multiple files and opening them at once (by pressing enter key).
You will have to look into developing shell extensions in order to achieve what you want. Just by using the registry to associate file types with your app, you are limited to passing just one file per command, which will end up opening your app once per file (which you have confirmed).
I guess you could also implement your app to allow only one instance running globally. That way, whenever a command comes in to open one more file, you could for example add it to a playlist or something.
Note that shell extensions have to be written in C++, Microsoft strongly advises to avoid managed code for this purpose.
You can find the documentation starting point here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb776778(v=vs.85).aspx
FileOpenPicker can do that (Code for UWP or Windows 8.1 desktop, with Windows 8.1 phone it's a bit trickier):
private static readonly string[] FileTypes = {
"aac", "adt", "adts", "mp3", "m3a", "m4a", "mpr", "3gp", "3g2",
"flac", "wav", "wma" };
...........
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
foreach (String fileType in FileTypes)
picker.FileTypeFilter.Add("." + fileType);
var list = await picker.PickMultipleFilesAsync();
FYI Your manifest must declare "Music Library" in Capabilities

File size limit in Windows Phone application using C#

I am new in Windows Phone application. In my application, when uploading files it is required to add file size limit not exceeding 50kb.
Code:
public sealed class OpenFileDialog
{
public string Filter { get; set; }
internal static object ShowDialog()
{
throw new NotImplementedException();
}
public static object DialogResult { get; set; }
public static string FileName { get; set; }
}
if (OpenFileDialog.ShowDialog() == System.Windows.Controls.DialogResult.OK)
{
FileStream fs = File.OpenRead(OpenFileDialog.FileName);
if (fs.Length > 51200)
{
MessageBox.Show("Image size must not exceed 50kb.");
return;
}
System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
myImage.Source = bmp;
}
but it show error,
Error:
namespace dialogresult doesn't exist in the namespace system.windows.controls(missing a assembly reference)
Anybody help me to solve this error?
You're attempting to use an enumeration that is part of the System.Windows.Forms namespace, and no such open file dialog exists in the Windows Phone 8 library. Without knowing more about your file access scenario, I will point out that your options would include:
Application Isolated Storage
Known Folders (WP 8.1 only including music, videos, photos, and SD card storage)
I'll point you to this general guide to accessing files programmatically which may take you to where you need to be specifically, but I should point out that since the most commonly accessible files on a phone device are rarely 50kb or less in size, we likely need more information about your use case.

Categories