IOutofmemory error with bitmap. windows mobile app - vb.net

I am developing a simple code to get the image from filedialog and i want it to be displayed in picturebox. but i get error "outofmemory" with few images.
here is my code
Dim srcmap As Bitmap
srcmap = New Bitmap(OpenFileDialog1.FileName)
Dim destbit As New Bitmap(220, 220)
Dim srcRec As New Rectangle(0, 0, srcmap.Width, srcmap.Height)
Dim destRec As New Rectangle(0, 0, 220, 220)
Dim g As Graphics
g = Graphics.FromImage(destbit)
g.DrawImage(srcmap, destRec,srcRec, GraphicsUnit.Pixel)
picturebox.Image = destbit

Mobile devices have limitted resources. Up to Windows CE 5 based OS (latest currently called Windows Embedded Handheld 6.5.3) each process gets only 32MB program memory. This memory is limitted by DLLs loaded by other processes and you may have 24MB or less available for a new process.
Instead of loading whole image data, which may 15MB (5MP image) or more you should load a thumbnail representation of the image data only. It does not make sense to load 15MB image data into a pictore box of for example only 1MB pixel data.
The OpenNetCF framework offers some classes to create thumbnails using streams. Other attempts to load the data and then resize it will fail.
I am sorry, but I only have C# code examples: here is an image helper class http://code.google.com/p/intermeccontrols/source/browse/DPAG7/Hasci.TestApp.And_Controls/IntermecControls/Hasci.TestApp.IntermecCamera3/ImageHelper.cs and here is how I used it to load 5MP images http://code.google.com/p/intermeccontrols/source/browse/DPAG7/Hasci.TestApp.And_Controls/IntermecControls/Hasci.TestApp.IntermecCamera3/IntermecCameraControl3.cs:
OpenNETCF.Drawing.Imaging.StreamOnFile m_stream;
Size m_size;
/// <summary>
/// this will handle also large bitmaps and show a thumbnailed version on a picturebox
/// see http://blog.opennetcf.com/ctacke/2010/10/13/LoadingPartsOfLargeImagesInTheCompactFramework.aspx
/// </summary>
/// <param name="sFileName">the name of the file to load</param>
private void showImage(string sFileName)
{
var stream = File.Open(sFileName, FileMode.Open);
m_stream = new StreamOnFile(stream);
m_size = ImageHelper.GetRawImageSize(m_stream);
System.Diagnostics.Debug.WriteLine("showImage loading " + sFileName + ", width/height = " + m_size.Width.ToString() + "/"+ m_size.Height.ToString());
//CameraPreview.Image = ImageHelper.CreateThumbnail(m_stream, CameraPreview.Width, CameraPreview.Height);
CameraSnapshot.Image = ImageHelper.CreateThumbnail(m_stream, CameraPreview.Width, CameraPreview.Height);
showSnapshot(true); //show still image
m_stream.Dispose();
stream.Close();
}

Related

Display WriteableBitmap video stream in GUI

I have the following code snippet that put a stream (NDI) into WriteableBitmap ready to be displayed:
VideoBitmap = New WriteableBitmap(xres, yres, dpiX, 96.0, PixelFormats.Pbgra32, Nothing)
VideoBitmap.WritePixels(New Int32Rect(0, 0, xres, yres), videoFrame.p_data, bufferSize, stride)
It comes from a WPF project that I need to replicate in Windows Form. In the original one this Video Stream was displayed by VideoSurface.Source = VideoBitmap where VideoSurface was an Image component.
I've tried to display it with:
Dim videoImg As New Image
videoImg.Source = VideoBitmap
PictureBox1.BackgroundImage = videoImg
but the last line gives an error: Value of type 'Image' cannot be converted to 'Image'.
How can I figure out this in the best way?

How do I add an image to a lightswitch silverPDF Document?

Within my Lightswitch desktop app (Silverlight client), I use silverPDF to create an invoice. All works well until I try to add an image (company logo).
My image is one that is saved to the database as image type (byte arrray) via the lightswitch image screen control. As far as I can tell I need to load the byte array into a memory stream then into silverPDF's XImage. Code snippet as follows:
Dim memStream As New MemoryStream(100)
memStream.Write(CompDetProp.CompanyLogo, 0, CompDetProp.CompanyLogo.Length)
Dim myimage As XImage = XImage.FromStream(memStream)
Dim x As Double = (250 - myimage.PixelWidth * 72 / myimage.HorizontalResolution) / 2
gfx.DrawImage(myimage, x, 10)
This compiles but I get an exception when run "The byte array is not a recognized imageformat."
I have also tried the following:
Dim memStream As MemoryStream = New MemoryStream(CompDetProp.CompanyLogo, 0, CompDetProp.CompanyLogo.Length)
Dim myimage As XImage = XImage.FromStream(memStream)
Dim x As Double = (250 - myimage.PixelWidth * 72 / myimage.HorizontalResolution) / 2
gfx.DrawImage(myimage, x, 10)
This second code block has the memory stream closing before it gets used - as far as I can tell.
How can I get the image into a stream that is read by silverPDF XImage before it closes and in the correct format?
After the comment from PDFsharp Expert I found that the image I was using was a .png file. I re saved the image as .jpg and the code worked. I now have an image on my invoice (although size constraints need to be played with to ensure correct fit). Thank you PDFsharp Expert.

Set source image of image control

I programming for Windows Phone 8.1. I use this way to create image and set source of image:
Dim AgreeBitmapImage As BitmapImage = New BitmapImage()
AgreeBitmapImage.setsource(New Uri("Assets/Image/Agree.png", UriKind.Relative))
//Above line gives an error
imgAccept = New Image
imgAccept.Height = 40
imgAccept.Width = 40
imgAccept.Source = AgreeBitmapImage
When I start the emulator, it doesn't work. Why? (Say error)
In Windows Phone 8.1, the resources like png should be get using ms-appx:
AgreeBitmapImage.UriSource =
New Uri("ms-appx:///Assets/Image/Agree.png", UriKind.Absolute)

Creating WP8 in-app video is not generating a .jpg thumbnail

I've been told that when I allow the user to create a video from within my app, a .jpg thumbnail image is supposed to be generated automatically. However, using windows phone power tools, I can see that only the video is generated, no image. Here is the code below:
EDIT: the QUESTION here, is HOW does one GET a thumbnail image from a given video that is saved in isolated storage?
' Set recording state: start recording.
Private Async Sub StartVideoRecording()
Try
App.ViewModel.IsDataLoaded = False
'isoStore = Await ApplicationData.Current.LocalFolder.GetFolderAsync("IsolatedStore")
strVideoName = GenerateVideoName()
isoFile = Await isoVideoFolder.CreateFileAsync(strVideoName, CreationCollisionOption.ReplaceExisting)
thisAccessStream = Await isoFile.OpenAsync(FileAccessMode.ReadWrite)
Await avDevice.StartRecordingToStreamAsync(thisAccessStream)
'save the name of the video file into the list of video files in isolated storage settings
Dim videoList As New List(Of InfoViewModel)
isoSettings = IsolatedStorageSettings.ApplicationSettings
If isoSettings.Contains("ListOfVideos") Then
videoList = isoSettings("ListOfVideos")
Else
isoSettings.Add("ListOfVideos", videoList)
End If
videoList.Add(New InfoViewModel With {.Name = strVideoName, .DateRecorded = Date.Now})
isoSettings("ListOfVideos") = videoList
isoSettings.Save()
isoSettings = Nothing
' Set the button states and the message.
UpdateUI(ButtonState.Recording, "Recording...")
Catch e As Exception
' If recording fails, display an error.
Me.Dispatcher.BeginInvoke(Sub() txtDebug.Text = "ERROR: " & e.Message.ToString())
End Try
End Sub
In Windows Phone 7.0 it wasn't possible using the "official" SDK to access the camera other than using CameraCaptureTask. But using Microsoft.Phone.InteropServices library it was possible to create a custom camera view in the application. If you used this VideoCamera class, it had an event called ThumbnailSavedToDisk, which might be what you have heard about. But apps using Microsoft.Phone.InteropServices was never allowed in the Windows Phone Marketplace. You can read more about it here.
To generate a thumbnail from a video file one solution would be to read up on how the MP4 file format works and extract one of the frames and use that as a thumbnail. Unfortunatly I haven't found any libraries that can do this.
Another, but far from optimal solution, would be to play the video in a MediaElement and then render that Control to a bitmap. This can be done with the following code (written in XAML/C#, I don't know VB.net, but should be easy to port):
<MediaElement
x:Name="VideoPlayer"
Width="640"
Height="480"
AutoPlay="True"
RenderTransformOrigin="0.5, 0.5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Stretch="Fill"
Canvas.Left="80"/>
And then to create the thumbnail:
// Set an event handler for when video has loaded
VideoPlayer.MediaOpened += VideoPlayer_MediaOpened;
// Read video from storage
IsolatedStorageFileStream videoFile = new IsolatedStorageFileStream("MyVideo.mp4", FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication());
VideoPlayer.SetSource(videoFile);
// Start playback
VideoPlayer.Play();
And then create the event handler which "captures" the thumbnail:
void VideoPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
Thread.Sleep(100); // Wait for a short time to avoid black frame
WriteableBitmap wb = new WriteableBitmap(VideoPlayer, new TranslateTransform());
thumbnailImageHolder.Source = wb; // Setting it to a Image in the XAML code to see it
VideoPlayer.Stop();
}
Here is how it looks when using a modified version of the Video Recorder Sample. (The small image with the blue border in the upper right corner is the thumbnail of the recorded video. Behind is the camera Viewer.)

Emgu circle detection using a webcam

I'm trying to write a program that detects a circle when you hold it in front of the webcam. I know how the circle detection works for an image, but I can't figure out how to get it to work with a webcam stream, using the following code:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ImageViewer viewer = new ImageViewer(); //create an image viewer
Capture capture = new Capture(); //create a camera capture
Application.Idle += new EventHandler(delegate(object sender, EventArgs e)
{ //run this until application closed (close button click on image viewer)
Image<Bgr, Byte> image = capture.QueryFrame();
//MemStorage storage = new MemStorage();
//Contour<Point> contours = image.FindContours();
//Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);
viewer.Image = image; //draw the image obtained from camera
});
viewer.ShowDialog(); //show the image viewer
}
As you can see I've tried using FindContours in the innermost loop but the program just freezes when I try running it, so I commented that particular part out. Can anyone tell me how to implement circle detection using a webcam?
You can use HoughCircle Method for circle detection
Image gray = img.Convert().PyrDown().PyrUp();
Gray cannyThreshold = new Gray(180);
Gray cannyThresholdLinking = new Gray(120);
Gray circleAccumulatorThreshold = new Gray(120);
CircleF[] circles = gray.HoughCircles(
cannyThreshold,
circleAccumulatorThreshold,
5.0, //Resolution of the accumulator used to detect centers of the circles
10.0, //min distance
5, //min radius
0 //max radius
)[0]; //Get the circles from the first channel
See Method HoughCircle