/// <summary>
        /// 非同步取得影像的OnCallback函數無法順利執行(目前不使用)
        /// </summary>
        /// <returns></returns>
        public Bitmap CaptureToImageAsyn()
        {
            try
            {
                stImage = null;
                bmp     = null;
                CStPixelFormatConverter m_Converter = new CStPixelFormatConverter();

                dataStream.RegisterCallbackMethod(OnCallback);
                dataStream.StartAcquisition(1);
                device.AcquisitionStart();

                if (SpinWait.SpinUntil(() => stImage != null, 10000))
                {
                    device.AcquisitionStop();
                    dataStream.StopAcquisition();

                    bool isColor = CStApiDotNet.GetIStPixelFormatInfo(stImage.ImagePixelFormat).IsColor;
                    if (isColor)
                    {
                        // Convert the image data to BGR8 format.
                        m_Converter.DestinationPixelFormat = eStPixelFormatNamingConvention.BGR8;
                    }
                    else
                    {
                        // Convert the image data to Mono8 format.
                        m_Converter.DestinationPixelFormat = eStPixelFormatNamingConvention.Mono8;
                    }
                    m_Converter.Convert(stImage, imageBuffer);
                    byte[]       imageData = imageBuffer.GetIStImage().GetByteArray();
                    MemoryStream ms        = new MemoryStream(imageData);
                    bmp = (Bitmap)Bitmap.FromStream(ms);
                }
                else
                {
                    throw new Exception("Camera(" + device.GetIStDeviceInfo().DisplayName + ") can not capture image!!");
                }
            }
            catch (Exception ex)
            {
                device.AcquisitionStop();
                dataStream.StopAcquisition();

                throw ex;
            }
            return(bmp);
        }
        //public void CaptureSaveSyn(string SavePath, string FileType)
        //{
        //    try
        //    {
        //        stImage = null;
        //        // 顯示裝置名稱
        //        Console.WriteLine("Device=" + device.GetIStDeviceInfo().DisplayName);

        //        //dataStream.RegisterCallbackMethod(OnCallback);

        //        // 主機端獲取影像
        //        dataStream.StartAcquisition(1);

        //        // 開始由相機取得影像
        //        device.AcquisitionStart();

        //        // 逾時超過5000ms後,回收儲存影像資料的暫存區
        //        // 使用 'using' 語法可在不需使用時,自動管理暫存區重新排隊操作
        //        using (CStStreamBuffer streamBuffer = dataStream.RetrieveBuffer(5000))
        //        {
        //            // 檢查取得的資料是否包含影像資料
        //            if (streamBuffer.GetIStStreamBufferInfo().IsImagePresent)
        //            {
        //                string sFT = FileType.ToLower();
        //                stImage = streamBuffer.GetIStImage();
        //                SavePath += (@"\" + device.GetIStDeviceInfo().DisplayName + @"\" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));
        //                if (sFT == "bitmap" || sFT == "bmp" || sFT == ".bmp")
        //                {
        //                    SavePath += ".jpg";
        //                }
        //                else if (sFT == "tiff" || sFT == "tif" || sFT == ".tif")
        //                {
        //                    SavePath += ".tif";
        //                }
        //                else if (sFT == "png" || sFT == ".png")
        //                {
        //                    SavePath += ".png";
        //                }
        //                else if (sFT == "jpeg" || sFT == "jpg" || sFT == ".jpg")
        //                {
        //                    SavePath += ".jpg";
        //                    stillImageFiler.Quality = 75;
        //                }
        //                else if (sFT == "csv" || sFT == ".csv")
        //                {
        //                    SavePath += ".csv";
        //                }
        //                else //要轉換的檔案格式(副檔名)錯誤
        //                    throw new Exception("File Type was wrong.");

        //                this.SaveImage(stImage, SavePath, sFT);

        //                device.AcquisitionStop();
        //                dataStream.StopAcquisition();
        //                //// 顯示接收影像的詳細資訊
        //                //Byte[] imageData = stImage.GetByteArray();
        //                //Console.Write("BlockId=" + streamBuffer.GetIStStreamBufferInfo().FrameID);
        //                //Console.Write(" Size:" + stImage.ImageWidth + " x " + stImage.ImageHeight);
        //                //Console.Write(" First byte =" + imageData[0] + Environment.NewLine);


        //                //var width = (int)stImage.ImageWidth;
        //                //var height = (int)stImage.ImageHeight;
        //                //myimg = new Bitmap(width, height);

        //                ////TODO: https://stackoverflow.com/questions/3474434/set-individual-pixels-in-net-format16bppgrayscale-image

        //                //for (var idx = 0; idx < imageData.Length; idx++)
        //                //{
        //                //    var val = imageData[idx];
        //                //    var color = Color.FromArgb(val, val, val);
        //                //    myimg.SetPixel(idx % width, idx / width, color);
        //                //}
        //            }
        //            else
        //            {
        //                // 如果取得的資料不含影像資料
        //                Console.WriteLine("Image data does not exist.");
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        device.AcquisitionStop();
        //        dataStream.StopAcquisition();

        //        throw ex;
        //    }
        //}

        public Bitmap CaptureToImageSyn()
        {
            try
            {
                stImage = null;
                bmp     = null;
                CStPixelFormatConverter m_Converter = new CStPixelFormatConverter();
                // 顯示裝置名稱
                Console.WriteLine("Device=" + device.GetIStDeviceInfo().DisplayName);

                //dataStream.RegisterCallbackMethod(OnCallback);

                // 主機端獲取影像
                dataStream.StartAcquisition(1);

                // 開始由相機取得影像
                device.AcquisitionStart();

                // 逾時超過5000ms後,回收儲存影像資料的暫存區
                // 使用 'using' 語法可在不需使用時,自動管理暫存區重新排隊操作
                using (CStStreamBuffer streamBuffer = dataStream.RetrieveBuffer(5000))
                {
                    // 檢查取得的資料是否包含影像資料
                    if (streamBuffer.GetIStStreamBufferInfo().IsImagePresent)
                    {
                        stImage = streamBuffer.GetIStImage();

                        #region 如果取得的影像是彩色,需經過轉換才能得到每Pixel以RGB排列的Byte[]
                        bool isColor = CStApiDotNet.GetIStPixelFormatInfo(stImage.ImagePixelFormat).IsColor;
                        if (isColor)
                        {
                            // Convert the image data to BGR8 format.
                            m_Converter.DestinationPixelFormat = eStPixelFormatNamingConvention.BGR8;
                        }
                        else
                        {
                            // Convert the image data to Mono8 format.
                            m_Converter.DestinationPixelFormat = eStPixelFormatNamingConvention.Mono8;
                        }
                        m_Converter.Convert(stImage, imageBuffer);
                        #endregion
                        //Byte[] imageData = stImage.GetByteArray();
                        byte[] imageData = imageBuffer.GetIStImage().GetByteArray();

                        var width  = (int)stImage.ImageWidth;
                        var height = (int)stImage.ImageHeight;

                        //如果影像是彩色的
                        if (isColor)
                        {
                            bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                        }
                        else//灰階影像
                        {
                            bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                            //// 下面的代碼是為了修改生成位圖的索引表,從偽彩修改為灰度
                            ColorPalette palette = bmp.Palette;
                            for (int i = 0; i < 256; i++)
                            {
                                palette.Entries[i] = Color.FromArgb(i, i, i);
                            }
                            bmp.Palette = palette;
                        }
                        // Lock the bits of the bitmap.
                        BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bmp.PixelFormat);
                        // Place the pointer to the buffer of the bitmap.
                        IntPtr ptr = bmpData.Scan0;

                        // fill in rgbValues
                        Marshal.Copy(imageData, 0, ptr, imageData.Length);
                        bmp.UnlockBits(bmpData);

                        //bmp.Save(@"D:/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".jpg", ImageFormat.Jpeg);
                    }
                    else
                    {
                        // 如果取得的資料不含影像資料
                        Console.WriteLine("Image data does not exist.");
                    }
                }
                return(bmp);
            }
            catch (Exception ex)
            {
                device.AcquisitionStop();
                dataStream.StopAcquisition();

                throw ex;
            }
            finally
            {
                device.AcquisitionStop();
                dataStream.StopAcquisition();
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            try
            {
                // Initialize StApi before using.
                using (CStApiAutoInit api = new CStApiAutoInit())

                    // Create a system object for device scan and connection.
                    using (CStSystem system = new CStSystem())

                        // Create a camera device object and connect to first detected device.
                        using (CStDevice device = system.CreateFirstStDevice())

                            // Create a DataStream object for handling image stream data.
                            using (CStDataStream dataStream = device.CreateStDataStream(0))
                            {
                                // Displays the DisplayName of the device.
                                Console.WriteLine("Device=" + device.GetIStDeviceInfo().DisplayName);

                                // Start the image acquisition of the host (local machine) side.
                                dataStream.StartAcquisition(nCountOfImagesToGrab);

                                // Start the image acquisition of the camera side.
                                device.AcquisitionStart();

                                // Get the path of the image files.
                                string fileNameHeader = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                                fileNameHeader += @"\" + device.GetIStDeviceInfo().DisplayName + @"\" + device.GetIStDeviceInfo().DisplayName;

                                bool isImageSaved = false;

                                // Get the file name of the image file of the StApiRaw file format
                                string fileNameRaw = fileNameHeader + ".StApiRaw";

                                // Retrieve the buffer of image data with a timeout of 5000ms.
                                using (CStStreamBuffer streamBuffer = dataStream.RetrieveBuffer(5000))
                                {
                                    // Check if the acquired data contains image data.
                                    if (streamBuffer.GetIStStreamBufferInfo().IsImagePresent)
                                    {
                                        // If yes, we create a IStImage object for further image handling.
                                        IStImage stImage   = streamBuffer.GetIStImage();
                                        Byte[]   imageData = stImage.GetByteArray();

                                        // Display the information of the acquired image data.
                                        Console.Write("BlockId=" + streamBuffer.GetIStStreamBufferInfo().FrameID);
                                        Console.Write(" Size:" + stImage.ImageWidth + " x " + stImage.ImageHeight);
                                        Console.Write(" First byte =" + imageData[0] + Environment.NewLine);

                                        // Create a still image file handling class object (filer) for still image processing.
                                        using (CStStillImageFiler stillImageFiler = new CStStillImageFiler())
                                        {
                                            // Save the image file as StApiRaw file format with using the filer we created.
                                            Console.Write(Environment.NewLine + "Saving " + fileNameRaw + "... ");
                                            stillImageFiler.Save(stImage, eStStillImageFileFormat.StApiRaw, fileNameRaw);
                                            Console.Write("done" + Environment.NewLine);
                                            isImageSaved = true;
                                        }
                                    }
                                    else
                                    {
                                        // If the acquired data contains no image data.
                                        Console.WriteLine("Image data does not exist.");
                                    }
                                }

                                // Stop the image acquisition of the camera side.
                                device.AcquisitionStop();

                                // Stop the image acquisition of the host side.
                                dataStream.StopAcquisition();

                                // The following code shows how to load the saved StApiRaw and process it.
                                if (isImageSaved)
                                {
                                    // Create a buffer for storing the image data from StApiRaw file.
                                    using (CStImageBuffer imageBuffer = CStApiDotNet.CreateStImageBuffer())

                                        // Create a still image file handling class object (filer) for still image processing.
                                        using (CStStillImageFiler stillImageFiler = new CStStillImageFiler())

                                            // Create a data converter object for pixel format conversion.
                                            using (CStPixelFormatConverter pixelFormatConverter = new CStPixelFormatConverter())
                                            {
                                                // Load the image from the StApiRaw file into buffer.
                                                Console.Write(Environment.NewLine + "Loading " + fileNameRaw + "... ");
                                                stillImageFiler.Load(imageBuffer, fileNameRaw);
                                                Console.Write("done" + Environment.NewLine);

                                                // Convert the image data to BGR8 format.
                                                pixelFormatConverter.DestinationPixelFormat = eStPixelFormatNamingConvention.BGR8;
                                                pixelFormatConverter.Convert(imageBuffer.GetIStImage(), imageBuffer);

                                                // Get the IStImage interface to the converted image data.
                                                IStImage stImage = imageBuffer.GetIStImage();

                                                // Save as Bitmap
                                                {
                                                    // Bitmap file extension.
                                                    string imageFileName = fileNameHeader + ".bmp";

                                                    // Save the image file in Bitmap format.
                                                    Console.Write(Environment.NewLine + "Saving " + imageFileName + "... ");
                                                    stillImageFiler.Save(stImage, eStStillImageFileFormat.Bitmap, imageFileName);
                                                    Console.Write("done" + Environment.NewLine);
                                                }

                                                // Save as Tiff
                                                {
                                                    // Tiff file extension.
                                                    string imageFileName = fileNameHeader + ".tif";

                                                    // Save the image file in Tiff format.
                                                    Console.Write(Environment.NewLine + "Saving " + imageFileName + "... ");
                                                    stillImageFiler.Save(stImage, eStStillImageFileFormat.TIFF, imageFileName);
                                                    Console.Write("done" + Environment.NewLine);
                                                }

                                                // Save as PNG
                                                {
                                                    // PNG file extension.
                                                    string imageFileName = fileNameHeader + ".png";

                                                    // Save the image file in PNG format.
                                                    Console.Write(Environment.NewLine + "Saving " + imageFileName + "... ");
                                                    stillImageFiler.Save(stImage, eStStillImageFileFormat.PNG, imageFileName);
                                                    Console.Write("done" + Environment.NewLine);
                                                }

                                                // Save as JPEG
                                                {
                                                    // JPEG file extension.
                                                    string imageFileName = fileNameHeader + ".jpg";

                                                    // Save the image file in JPEG format.
                                                    stillImageFiler.Quality = 75;
                                                    Console.Write(Environment.NewLine + "Saving " + imageFileName + "... ");
                                                    stillImageFiler.Save(stImage, eStStillImageFileFormat.JPEG, imageFileName);
                                                    Console.Write("done" + Environment.NewLine);
                                                }

                                                // Save as CSV
                                                {
                                                    // CSV file extension.
                                                    string imageFileName = fileNameHeader + ".csv";

                                                    // Save the image file in CSV format.
                                                    Console.Write(Environment.NewLine + "Saving " + imageFileName + "... ");
                                                    stillImageFiler.Save(stImage, eStStillImageFileFormat.CSV, imageFileName);
                                                    Console.Write("done" + Environment.NewLine);
                                                }
                                            }
                                }
                            }
            }
            catch (Exception e)
            {
                // If any exception occurred, display the description of the error here.
                Console.Error.WriteLine("An exception occurred. \r\n" + e.Message);
            }
            finally
            {
                // Wait until the Enter key is pressed.
                Console.WriteLine("\r\nPress Enter to exit.");
                Console.ReadLine();
            }
        }