I am a newbie to mono C# programming in raspbian os (pi3 b). I have taken a sample code for fingerprint scanner application in C# mono from this github link, Now I am running the same application in Raspbian os under the pi3 b board.
Now after scanning the user finger image, I want to display into my winform PictureBox.
once the application scans each finger then it will send the byte[] to the UI using the below callback method.
private void FingerPrintlib_OnEnrollImageResult(byte[] enrollImage, int count)
{
//lblinstruction.Invoke((MethodInvoker)delegate
//{
// lblinstruction.Visible = false;
//});
if (count == 0)
{
pictureBox4.Invoke((MethodInvoker)delegate
{
//pictureBox4.Image = byteArrayToImage(enrollImage);
pictureBox4.SizeMode = PictureBoxSizeMode.StretchImage;
});
}
else
{
pictureBox5.Invoke((MethodInvoker)delegate
{
//pictureBox5.Image = byteArrayToImage(enrollImage);
pictureBox5.SizeMode = PictureBoxSizeMode.StretchImage;
});
}
}
I am a newbie to mono C# programming in raspbian os (pi3 b). I have written a fingerprint scanner application in C# and using mono, I am running the same application in Raspbian os under the pi3 board.
Now after scanning the user finger image, I want to display into my PictureBox.
once the lib scans each finger then it will send the byte[] to the UI using the below callback method.
private void FingerPrintlib_OnEnrollImageResult(byte[] enrollImage, int count)
{
//lblinstruction.Invoke((MethodInvoker)delegate
//{
// lblinstruction.Visible = false;
//});
if (count == 0)
{
pictureBox4.Invoke((MethodInvoker)delegate
{
//pictureBox4.Image = byteArrayToImage(enrollImage);
pictureBox4.SizeMode = PictureBoxSizeMode.StretchImage;
});
}
else
{
pictureBox5.Invoke((MethodInvoker)delegate
{
//pictureBox5.Image = byteArrayToImage(enrollImage);
pictureBox5.SizeMode = PictureBoxSizeMode.StretchImage;
});
}
}
Image byteArrayToImage(byte[] byteArrayIn)
{
try { MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
when I execute the above code I am getting an exception like
A null reference or invalid value was found [GDI+ status:
InvalidParameter]
so how can I solve this issue and display the image file into my application?
Thanks
The code below works just fine:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace ImageLoad
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
byte[] data = File.ReadAllBytes("test.jpg");
this.pictureBox1.Image = GetImage(data);
}
private static Image GetImage(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
return (Image.FromStream(ms));
}
}
}
}
New Windows form project, add a picture box to form, copy test.jpg file to Debug directory and use code above. No problem. Image was loaded.
Related
I need to convert a VLC video stream (working) in my WPF app to a bmp for Xzing to be able to decode,
I can decode using a usb or the onboard webcam.
But how to get the 2 together??
Been searching all over and have tried some solutions but nothing seems to work, might be me as i'm pretty new to C#
Thanks
I tried this piece of code:
public static void Get_Frame(Vlc.DotNet.Forms.VlcControl vlc)
{
try
{
if (File.Exists(Temp_Frame_Filename))
{
File.Delete(Temp_Frame_Filename);
}
vlc.TakeSnapshot(Temp_Frame_Filename, width: (uint)vlc.Size.Width, (uint)vlc.Size.Height);
}
catch
{
MessageBox.Show("No Code");
}
}
I cant get it to work because I don't know how to call it,
I want to call it from a dispatch timer but I get errors.
Sorry for not answering questions correctly, will get the hang of this forum.
Try get the whole function in:
/// <summary>
/// Draw the video box into an image
/// </summary>
/// <param name="vlc"></param>
/// <returns></returns>
public static void Get_Frame(Vlc.DotNet.Forms.VlcControl vlc)
{
try
{
if (File.Exists(Temp_Frame_Filename))
{
File.Delete(Temp_Frame_Filename);
}
vlc.TakeSnapshot(Temp_Frame_Filename, width: (uint)vlc.Size.Width, (uint)vlc.Size.Height);
}
catch
{
MessageBox.Show("No Code");
}
}
I tried doing this:
void Codetimer_Tick(object sender, EventArgs e)
{
ZXing.BarcodeReader Reader = new ZXing.BarcodeReader();
Result result = Reader.Decode(Temp_Frame_Filename);
if (result != null) TxtScannedResult.Text = result.ToString();
}
Get an error cannot convert from string to system.drawingbitmap.
Thanks
I think I went down the wrong path with that attempt,
I somehow need to convert a VLCVideo stream to bitmap for Xzing
any ideas please
I made a little test with Vlc.DotNet.Wpf 3.0.0 and ZXing.Net 0.16.5.
I'm not sure why you are speaking about a WPF app but then you are using the Vlc.DotNet.Forms namespace. I used the Vlc.DotNet.Wpf.VlcControl.
Here is the proof of concept code (perhaps there is a better solution for threading and locking, but it works):
First, I added the VlcControl to my WPF form:
<Wpf:VlcControl Name="vlcControl" HorizontalAlignment="Left" Height="380" Margin="87,10,0,0" VerticalAlignment="Top" Width="367" Loaded="VlcControl_Loaded"/>
And here is the code behind:
private int isWorking;
private System.Threading.Timer decodingTimer;
private ZXing.IBarcodeReader<BitmapSource> reader = new ZXing.Presentation.BarcodeReader();
private void VlcControl_Loaded(object sender, RoutedEventArgs e)
{
((VlcControl)sender).SourceProvider.CreatePlayer(new DirectoryInfo(#"C:\Program Files\VideoLAN\VLC"));
((VlcControl)sender).SourceProvider.MediaPlayer.SetMedia(new FileInfo(#"How Barcodes Work - YouTube.mp4"));
((VlcControl)sender).SourceProvider.MediaPlayer.Play();
decodingTimer = new System.Threading.Timer(DoDecoding, null, 500, 500);
}
private void DoDecoding(object state)
{
if (Interlocked.Increment(ref isWorking) == 1)
{
this.Dispatcher.BeginInvoke((Action) (() =>
{
try
{
var bitmap = vlcControl.SourceProvider.VideoSource as InteropBitmap;
if (bitmap != null)
{
var result = reader.Decode(bitmap);
if (result != null)
{
MessageBox.Show(result.Text);
}
}
}
catch (Exception )
{
// add handling here
}
finally
{
Interlocked.Decrement(ref isWorking);
}
}));
}
else
{
Interlocked.Decrement(ref isWorking);
}
}
Thank you so much for your help, I tried your solution and it works perfectly.
I have implemented in my solution and am getting the following error:
Object reference not set to an instance of an object.
Any ides why?
Here are some code snippets:
public partial class MainWindow : Window
private ZXing.IBarcodeReader<BitmapSource> reader = new ZXing.Presentation.BarcodeReader();
private System.Threading.Timer decodingTimer;
and
private void DoDecoding(object state)
{
this.Dispatcher.BeginInvoke((Action)(() =>
{
try
{
InteropBitmap bitmap = videoSin.SourceProvider.VideoSource as InteropBitmap;
if (bitmap != null)
{
var result = reader.Decode(bitmap);
if (result != null)
{
MessageBox.Show(result.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
));
}
The Video stream works and I only get the error when I present a barcode to the camara.
Thanks
I try to get screenshot of android device using appium since there is no solution with appium to get video/see app on real time.
I have function of C# to get image (screenshot)
public Image GetImages()
{
Image screen_shot = null;
try
{
if (driverAndroid == null)
{
return screen_shot;
}
var screenshot = ((ITakesScreenshot)driverAndroid).GetScreenshot();
var ms = new MemoryStream(screenshot.AsByteArray);
screen_shot = Image.FromStream(ms);
ms.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return screen_shot;
}
and I try to call it using ironpython
class HelloWorldForm(Form):
def __init__(self):
app = test()
Form.__init__(self)
pictureBox = PictureBox()
image = app.GetImages()
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage
pictureBox.Image = image
pictureBox.Dock = DockStyle.Fill
self.Controls.Add(pictureBox)
self.Show()
Application.EnableVisualStyles()
form = HelloWorldForm()
Application.Run(form)
I can get only 1st image for now, I put it in while function but it does not work.
Any solution or modification on the code so that I can get screenshot on real time, like a video.
I want to add a custom tile to the Microsoft Band through Microsoft Band SDK in a UWP app for Windows Phone. Here is my sample code.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
try
{
// Get the list of Microsoft Bands paired to the phone.
var pairedBands = await BandClientManager.Instance.GetBandsAsync();
if (pairedBands.Length < 1)
{
Debug.WriteLine("This sample app requires a Microsoft Band paired to your device.Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.");
return;
}
// Connect to Microsoft Band.
using (var bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
{
// Create a Tile with a TextButton on it.
var myTileId = new Guid("12408A60-13EB-46C2-9D24-F14BF6A033C6");
var myTile = new BandTile(myTileId)
{
Name = "My Tile",
TileIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconLarge.png"),
SmallIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconSmall.png")
};
// Remove the Tile from the Band, if present. An application won't need to do this everytime it runs.
// But in case you modify this sample code and run it again, let's make sure to start fresh.
await bandClient.TileManager.RemoveTileAsync(myTileId);
// Create the Tile on the Band.
await bandClient.TileManager.AddTileAsync(myTile);
// Subscribe to Tile events.
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private async Task<BandIcon> LoadIcon(string uri)
{
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
WriteableBitmap bitmap = new WriteableBitmap(1, 1);
await bitmap.SetSourceAsync(fileStream);
return bitmap.ToBandIcon();
}
}
If I run this code nothing happend. The app connected to Microsoft Band, but is not able to add a tile. The method AddTileAsync(myTile); Returns false and doesn't add a tile to the Microsoft Band.
If I try this code in a Windows Phone 8.1 app it works, but not in the UWP app.
Any ideas?
Update
Here is the sample app as download. Maybe this can help.
maybe this would help, coming from the documentation of MS Band
using Microsoft.Band.Tiles;
...
try
{
IEnumerable<BandTile> tiles = await bandClient.TileManager.GetTilesAsync();
}
catch (BandException ex)
{
//handle exception
}
//determine if there is space for tile
try
{
int tileCapacity = await bandClient.TileManager.GetRemainingTileCapacityAsync();
}
catch (BandException ex)
{
//handle ex
}
//create tile
WriteAbleBitmap smallIconBit = new WriteAbleBitmap(24, 24);
BandIcon smallIcon = smallIconBit.ToBandIcon();
WriteAbleBitmap largeIconBit = new WriteAbleBitmap(48, 48);//46, 46 for MS band 1
BandIcon largeIcon = largeIconBit.ToBandIcon();
Guid guid = Guid.NewGuid();
BandTile tile = new BandTile(guid)
{
//enable Badging
IsBadgingEnabled = true,
Name = "MYNAME"
SmallIcon = smallIcon;
TileIcon = largeIcon;
};
try
{
if(await bandClient.TileManager.AddTileAsync(tile))
{
///console print something
}
}
catch(BandException ex)
{
//blabla handle
}
I think the issue may be you're setting the writeable bitmap size to (1,1)?
I have this method working:
public static class BandIconUtil
{
public static async Task<BandIcon> FromAssetAsync(string iconFileName, int size = 24)
{
string uri = "ms-appx:///" + iconFileName;
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri, UriKind.RelativeOrAbsolute));
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
WriteableBitmap bitmap = new WriteableBitmap(size, size);
await bitmap.SetSourceAsync(fileStream);
return bitmap.ToBandIcon();
}
}
}
My question is pretty straightforward. I need to display a print preview dialog in a multi-user ERP environment. It speaks for itself that printing should be as fast as possible.
However, if I use the code below, it takes about 10! seconds before the preview is displayed and is fully generated. This is without database access or any other CPU intensive operations.
Is there any way or method to improve this performance? I'm also able to use WPF, should that be necessary.
I've noticed that if you generate the preview, close it, and then quickly generate it again, it responds much faster, about a second or two. If you then wait another 5 seconds or so, generate it again, it takes about 10 seconds again.
I'm guessing some type of caching is going on, but don't have a clue what's actually happening.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PrintPerformanceTests
{
public class PrintPreviewTest
{
private string printerName;
private PrintPreviewDialog printPreviewDialog1;
private PrintDocument printDocument1 = new PrintDocument();
private Random random = new Random();
public string PrinterName
{
get { return printerName; }
set { printerName = value; }
}
public PrintPreviewDialog PrintPreviewDialog
{
get { return printPreviewDialog1; }
set { printPreviewDialog1 = value; }
}
public PrintPreviewTest(string printerName, PrintPreviewDialog printPreviewDialog)
{
this.PrinterName = printerName;
this.PrintPreviewDialog = printPreviewDialog;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
}
public void GenerateRandomPrintPreview()
{
Cursor.Current = Cursors.WaitCursor;
try
{
PrintPreviewDialog.Document = printDocument1;
PrintPreviewDialog.ShowDialog();
}
catch (Exception exc)
{
Cursor.Current = Cursors.Default;
MessageBox.Show(exc.ToString());
}
finally
{
Cursor.Current = Cursors.Default;
}
}
void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
using(Font f = new Font("Arial", 10f))
{
for (int i = 0; i < 20; i++)
{
string txt = "Random string " + i.ToString();
e.Graphics.DrawString(txt, f, Brushes.Black, new PointF(random.Next(10, 200), random.Next(10,280)));
}
}
e.HasMorePages = false;
}
}
}
usage:
PrintPreviewTest pt = new PrintPreviewTest(tbPrinter.Text, printPreviewDialog);
pt.GenerateRandomPrintPreview();
In my experience this startup delay is related to initialization of printer parameters. When you set printer name (especially network printer name) and create print preview dialog, it first connects to the specified printer and checks it's settings (paper size etc.). It takes a lot of time. The only way (IMHO) to overcome this issue is to create your own print preview dialog that initializes printer settings in separate thread.
I am having a strange problem.I am using the Windows API Code Pack for Microsoft .NET Framework for displaying custom thumbnails for my custom file extensions.I have used the Microsoft.WindowsAPICodePack.ShellExtensions namespace methods as mentioned in the documentation and I can successfully show a thumbnail.But i am encountering a strange problem.While the shell thumbnail handler is registered, I cannot delete the file for which the thumbnail is shown.The file gets deleted alright for normal delete but while using Shift+del the file disappears form explorer without errors but will return when i refresh the folder.The file will stay there until I restart explorer.exe process or if I focus the window and wait for 60secs the file disappears on its own.The returned file doesn't allow to get deleted again giving an access denied error message.I tried using LockHunter and it shows that explorer.exe is locking the file.I am confused guys.What am I doing wrong ?. How can I fix this?.
I am using Windows 7 64 bit,visual studio 2010
My code is as follows
namespace CustomThumbnail
{
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("CustomThumbnail.XYZThumbnailer")]
[Guid("439a0bd3-8a44-401d-931c-3021ad8b1ad6")]
[ThumbnailProvider("XYZThumbnailer", ".xyz", ThumbnailAdornment = ThumbnailAdornment.VideoSprockets)]
public class MyThumbnailProvider : ThumbnailProvider, IThumbnailFromStream
{
public Bitmap ConstructBitmap(System.IO.Stream stream, int sideSize)
{
try
{
LogMessageToFile("Hello Stream");
XyzFileDefinition file = new XyzFileDefinition(stream);
using (MemoryStream mstream = new MemoryStream(Convert.FromBase64String(file.EncodedImage)))
{
LogMessageToFile("using Stream");
Bitmap bmp = new Bitmap(mstream);
LogMessageToFile(bmp.ToString());
return bmp;
}
}
catch (Exception ex)
{
LogMessageToFile(ex.ToString());
throw;
}
}
public void LogMessageToFile(string msg)
{
System.IO.StreamWriter sw = System.IO.File.AppendText(#"D:\test\testdoc.txt");
try
{
string logLine = System.String.Format(
"{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine(logLine);
}
finally
{
sw.Close();
}
}
}
}
New Code
public Bitmap ConstructBitmap(Stream stream, int sideSize)
{
try
{
Assembly assembly = Assembly.LoadFile(#"C:\Users\xxxx\Documents\Visual Studio 2010\Projects\MyThumbnailTest\Bin\Data\Data.dll");
Type type = assembly.GetType("Data.ThumbnailData");
MethodInfo foo = type.GetMethod("GetThumbnail");
var c= foo.Invoke(Activator.CreateInstance(type), new object[] { stream });
return (Bitmap)c;
}
catch (Exception ex)
{
LogMessageToFile("error "+ex.Message.ToString());
throw ex;
}
finally
{
stream.Close();
stream.Dispose();
}
}
And my GetThumbnail Method goes like this
public class ThumbnailData
{
public Bitmap GetThumbnail(Stream stream)
{
using (ZipFile zip = ZipFile.Read(stream))
{
ZipEntry image = zip.Entries.Where(p => p.FileName.ToLower().IndexOf(".png") > 0).FirstOrDefault();
if (image != null)
{
using (MemoryStream ms = new MemoryStream())
{
image.Extract(ms);
Bitmap bmp = new Bitmap(ms);
return bmp;
}
}
return new Bitmap(150, 150);
}
}
}
Without seeing the code, this is all I can think of:
Is your custom thumbnail code not closing the Stream for the file after it produces the thumbnail?
As my comment suggested try this:
public Bitmap ConstructBitmap(System.IO.Stream stream, int sideSize)
{
try
{
LogMessageToFile("Hello Stream");
XyzFileDefinition file = new XyzFileDefinition(stream);
using (MemoryStream mstream = new MemoryStream(Convert.FromBase64String(file.EncodedImage)))
{
LogMessageToFile("using Stream");
Bitmap bmp = new Bitmap(mstream);
LogMessageToFile(bmp.ToString());
return bmp;
}
}
catch (Exception ex)
{
LogMessageToFile(ex.ToString());
throw;
}
finally
{
stream.Close();
}
}