Depth data convert to Image Bgr, Byte in a windows store project

Hi,
i use EmguCv to process depth data from Kinect v2. Now i want to do it in a windows store 8.1 app. In older project i use these code to convert from writable bitmap:
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(depthBitmap));
MemoryStream ms = new MemoryStream();
encoder.Save(ms);
Bitmap b = new Bitmap(ms);
Image<Bgr, Byte> openCVImg = new Image<Bgr, Byte>(b);
I the project i miss the bitmap class, i search the whole day for a solution...
Thx for any hlp
René

The answer with help from Canming Huang (Thx):
private Image<Bgr, Byte> Array2IImage(byte[] pixelArray)
GCHandle dataHandle = GCHandle.Alloc(pixelArray, GCHandleType.Pinned);
try
using (Image<Bgra, Byte> image = new Image<Bgra, byte>(this.pixelWidth, this.pixelHeight, this.pixelWidth * this.cbytesPerPixel, dataHandle.AddrOfPinnedObject()))
return image.Convert<Bgr, Byte>();
finally
dataHandle.Free();

Similar Messages

  • Convert Below Java code equivalent to c# windows store app.

    Hi
    please help me " To convert Below Java code equivalent to c# windows store app."
    private String SecretKey = "enctsbqrm6hxyjfa";
        public byte[] encrypt(String text) throws Exception
            if(text == null || text.length() == 0)
                throw new Exception("Empty string");
            // convert key to bytes
            byte[] keyBytes = SecretKey.getBytes("UTF-8");
            // Use the first 16 bytes (or even less if key is shorter)
            byte[] keyBytes16 = new byte[16];
            System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));
            // convert plain text to bytes
            byte[] plainBytes = text.getBytes("UTF-8");
            // setup cipher
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            //byte[] iv = new byte[16]; // initialization vector with all 0
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // encrypt
            byte[] encrypted = cipher.doFinal(plainBytes);
            return encrypted;
      Thanks            
      Nitin

    Hello Nitin,
    Your current requirement is beyond the scope of our support for this fourm which is used to Discuss and ask questions about .NET Framework Base Classes (BCL) such as Collections, I/O, Regigistry, Globalization, Reflection.
    If you want to know how to encrypt/decrypt in windows store app, I suggest that you could post a it to:
    https://social.msdn.microsoft.com/Forums/windowsapps/en-US/home?forum=winappswithcsharp
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to create a file in application data local folder which is not hidden in windows store app?

    I want to create a log file in ApplicationData local folder.
         m_StorageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(m_Name.Replace(" ", "_") + ".log",
                              CreationCollisionOption.OpenIfExists);
    First time when my app is launched, the file gets created and logs are written.
    When I close my app, and re run the app once again, the log file that was created is now hidden and when i try to call
    the code :    m_StorageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(m_Name.Replace(" ", "_") + ".log",
                              CreationCollisionOption.OpenIfExists);
    m_StorageFile is NULL.
    How can i prevent the file from becoming Hidden or ReadOnly.
    Thanks

    Here is a very simple sample that works fine.  Start with this and see what you are doing different.
    XAML:
    <Page
    x:Class="LocalStorage.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LocalStorage"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Loaded="Page_Loaded">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox x:Name="outputTxt" HorizontalAlignment="Left" Margin="76,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" AllowDrop="True" PlaceholderText="No Data read from local file" Width="791"/>
    <Button Content="Store Data" HorizontalAlignment="Left" Margin="73,145,0,0" VerticalAlignment="Top" Click="Button_Click" />
    </Grid>
    </Page>
    C#
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Storage;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    namespace LocalStorage
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    public MainPage()
    this.InitializeComponent();
    private async void Button_Click(object sender, RoutedEventArgs e)
    if (m_StorageFile != null)
    try
    string userContent = outputTxt.Text;
    if (!String.IsNullOrEmpty(userContent))
    await FileIO.WriteTextAsync(m_StorageFile, userContent);
    else
    // should be some info to write
    catch (FileNotFoundException)
    // do something
    private StorageFile m_StorageFile;
    private async void createFileOrGetFile()
    m_StorageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("sample.log", CreationCollisionOption.OpenIfExists);
    private async void Page_Loaded(object sender, RoutedEventArgs e)
    createFileOrGetFile();
    if (m_StorageFile != null)
    try
    string fileContent = await FileIO.ReadTextAsync(m_StorageFile);
    outputTxt.Text = fileContent;
    catch (FileNotFoundException)
    // do something!
    Jeff Sanders (MSFT)
    @jsandersrocks - Windows Store Developer Solutions
    @WSDevSol
    Getting Started With Windows Azure Mobile Services development?
    Click here
    Getting Started With Windows Phone or Store app development?
    Click here
    My Team Blog: Windows Store & Phone Developer Solutions
    My Blog: Http Client Protocol Issues (and other fun stuff I support)

  • Convert jpg image to array of integers and store in file

    For a project that I am working on I need to be able to take the black and white jpg images that I am using and convert each pixel into either a -1 or +1 according to if the pixel color is white or black. Then, once I have an array of those values, I need to store the array to a file. Can this be done? Can PixelGrabber accomplish this task? Thanks in advance!
    Keith Pemberton

    Yes
    PixelGrabber pg = new PixelGrabber(myImage, 0, 0, width, height, pixels, 0, width);

  • Reading an image in byte form

    hii guys
    i m trying to read an image and convert it to byte array and later to do some change in that byte array and later recreate a new image.
    For that i m using FileInputStream and FileOutputStream and its read and write methods
    but now i dont know how to append that byte and recreate that image.
    actually i want to do that , convert the image in byte array form and replacing some bytes of the image by my text msg bytes and recreate a new image.
    how an i do that.
    plz help me.
    its urgent.

    import java.io.*;
    class image
    public static void main(String[] arg) throws IOException
    String msg;
    int len,i;
    FileInputStream fin;
    FileOutputStream fout;
    try
    try
    fin=new FileInputStream("01.jpg");
    catch( Exception e)
    System.out.println("Input image not found");
    return;
    try
    fout=new FileOutputStream("001.jpg");
    catch( Exception e)
    System.out.println("output image cannt be created");
    return;
    catch(Exception e)
    System.out.println("output image cannt be created");
    return;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the secret msg :: ");
    msg=br.readLine();
    byte[] msg1=msg.getBytes();
    len=msg1.length;
    System.out.println(len);
    for(i=0;i<len;i++)
    System.out.println(msg1);
    try
    do
    byte by=(byte)fin.read();
    //System.out.print(" "+by);
    if(fin.available()>0)
    fout.write(by);
    }while(fin.available()>0);
    catch(Exception e)
    System.out.println("File error");
    fin.close();
    fout.close();
    till now i only imputed the sg , change it into byte form .
    now i want to replace the msg bytes into the image byte as :- 1 image byte ,1 msg byte, 1 image byte , 1 msg byte........ so on
    until the msg bytes are not finished.

  • Conversion of image into byte array

    I have a problem in converting .png image into bytestream, if anyone can help in this pls do so.....

    Hi,
    To convert an Image to bytes you can use the Image.getRGB() method.
    http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#getRGB(int[], int, int, int, int, int, int)
    -Henrik

  • Image to byte array

    hello,
    how can i get an image in jar file as a byte[] or can i convert an image to byte[]?
    thx...

    To read a bytes from a jar file, use a JarInputStream. If you're just trying to read bytes from a jar, it doesn't make any difference whether it's an image or not.
    To get the bytes from an Image, you need to put more information in your question - are you talking about an image file, like a JPEG or TIFF? What do you want to do with it? Or are you talking about an Image object in Java? If so, which specific concrete subclass, and what do you want to do with it?

  • Reader version 9 not opening some files: error "insufficient data for an image"

    Adobe reader version 9 is having difficulties opening PDF's, mainly with PDF's that contain charts or jpg's.
    When using Google Chrome browser, I get the message "insufficient data for an image."
    I am using windows XP.  When I open these same PDF's using Internet Explorer, they display fine, but some of them don't print, and cause the printing spooler to malfunction, i.e., the print spooler begins turning itself off repeatedly, and then I can't print anything from any program. This print spooler problem is really difficult to solve. But I think all of this is originating from some inability of the current version of Adobe to handle some PDF's, which is a recent phenomenon. I've never had problems like this before with previous versions.

    I've had the same problem then it got "magically" fixed by itself. A big thanks to Adobe for their updates

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • How to convert base64 data to an image

    Hello, my enterprise application is receiving base64 enocoded image data in an xml file. Now I need to convert it to a native image formats like jpeg/jpg/tiff/pdf etc. Does anybody know if there are any Java apis (both free/paid) which let you do this. Actually I would not have any idea of what type of image it was when it was initially encoded to base64 format. I am looking for an API/technique that can convert base64 data to any image depending on what I want at runtime.
    Thanks a lot in advance.
    R

    Hi there,
    I've had to deal with exactly the same problem myself. The images I had to deal with were all TIFF files, and that was okay, I'd say one of your first steps would be to find out what format these images are in.
    I used a SAX Content Handler to pull the base 64 image data out of the XML into a String, and then converted the Base 64 String into a byte array. From there I could either simply write the byte array to a file, or if I wanted use ImageIO to create an Image object, work with the metadata or even save it in a different format, though I never actually did that.
    Anyway, here is some code I whipped up to convert the String to a byte array, then write the byte array to disk. Let us know how you get along!
          * Writes a byte array to a file.
          * @param result          String containing base64 image data     
          * @param fileName     File name to write the converted image to
         public static void writeTiff(byte[] result, String fileName) throws IOException {          
              FileOutputStream out = new FileOutputStream(fileName, true);
              out.write(result);
              out.close();
          * Converts a String of base 64 image data, captured from XML, into a byte array.
          * @param      image     A Base 64 String          
          * @return      byte[]          
         public static byte[] convertTiff(String image) throws IOException {          
              byte[] result = new sun.misc.BASE64Decoder().decodeBuffer(image);
              return result;
         }

  • BGR bytes to Image

    I have loads of data, in the form of a byte array in one long list of BGRBGRBGR values. There is a bufferedImage type BGR byte:
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    but how can i write my values into it? I tried getting a WritableRaster, but the arguments for that are int int int int[]
    raster.setPixels(int startx, int starty, int width, int height, int[] pixels)
    (which I havnt had any luck with iether, all my integer pixles are black..)
    So far, Ive been trying to use int pixel values to just get something working:
    public static Image getImageFromArray(int[] pixels, int width, int height) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //image.
            int pix[] = new int[width*height*3];
            for (int i = 0 ; i < width*height ; i +=3){
                 //pix=Color.BLUE.getRGB();
         pix[i]=255;
         pix[i+1]=0;
         pix[i+2]=0;
    WritableRaster raster = (WritableRaster) image.getData();
    raster.setPixels(0,0,width,height,pix);
    return image;
    }but its all black (oh, and i thought the int values contained the RBG (so i would use Color.BLUE>getRGB();) but the setPixels gets an arrayindex out of bounds for anything less than 3*width*height, suggesting its in int rgb format...
    Edited by: IJustWantToSayHelloWorld on Aug 13, 2010 8:59 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    This method would wrap your byte[] array into a BufferedImage.
    /**Wraps a BGRBGR... byte array into a TYPE_3BYTE_BGR BufferedImage*/
    public static BufferedImage wrapInImage(byte[] imgData, int w, int h) {
        DataBuffer db = new DataBufferByte(imgData,w * h * 3);
        WritableRaster raster = WritableRaster.createInterleavedRaster(
                db,w,h,w*3, 3, new int[]{2,1,0}, null);
        ColorModel colorModel = new ComponentColorModel(
                        ColorSpace.getInstance(ColorSpace.CS_sRGB),
                        new int[]{8,8,8}, false, false,
                        Transparency.OPAQUE,
                        DataBuffer.TYPE_BYTE);
        return new BufferedImage(colorModel, raster,false, null);
    }Because you create the image from your own byte array, the image is guaranteed not be hardware accelerated. Graphical operations to or from the image may not be as fast as they can.
    This method would create a new image (may be hardware accelerated), at the cost of memory and performance in creating the image.
    /**Creates a new TYPE_3BYTE_BGR BufferedImage from a BGRBGR... byte array.*/
    public static BufferedImage createImage(byte[] imgData, int w, int h) {
        DataBuffer db = new DataBufferByte(imgData,w * h * 3);
        WritableRaster srcRast = WritableRaster.createInterleavedRaster(
                db,w,h,w*3, 3, new int[]{2,1,0}, null);
        BufferedImage copy = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
        //can be done several ways including row by row (which is not done here)
        copy.getRaster().setDataElements(0,0,srcRast);
        return copy;
    }

  • Convert colour images to grayscale images & get pixel data from them

    Is the code below correct to convert colour images to grayscale images in Java?
    public void convertToGrayscale (String sourceName,String destName) throws Exception {
    JPEGImageDecoder decoder=JPEGCodec.createJPEGDecoder(new FileInputStream(sourceName));
    JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(new FileOutputStream(destName));
    BufferedImage sourceImg=decoder.decodeAsBufferedImage();
    BufferedImageOp op =new ColorConvertOp(
              ColorSpace.getInstance(ColorSpace.CS_GRAY),null);
         BufferedImage destImg = op.filter(sourceImg,null);
    encoder.encode(destImg);
    decoder = null;
    encoder = null;
    When I get grayscale images from the code below, I would like to access the pixels of those images. So I tried to do:
    byte[] dd=((DataBufferByte)mImage.getRaster().getDataBuffer()).getData();
    BUT the data result array is not 0-255. Could anyone suggest how to obtain pixel data from grayscale images?
    In case that my code shown is not correct or suitable, please give your advice. What I would like to do are in the steps as follows:
    1 change 100*70 jpeg-images to 100*70 grayscale images.
    2 create two dimensional array of pixel data (example [100][70]) from converted images. The number in the array should be between 0-255, right??? And 0 refers to black colour and 255 refers to white colour???
    I am confused about grayscale images. Please help.
    Thank you so much

    I am not sure i understand what is the problem exactly.
    Structure of DataBuffer is described by SampleModel used by same Raster
    object. E.g. it might be 1 byte per xipex or 4 bytes per pixel.
    In your example convertToGrayscale saves images to file as JPEG and
    it seems you later read it back. It is possible what image you read back
    is not greyscale but ARGB and data buffer has different format.
    Technically, if you just need level of grey you may simply
    call getRGB on your output image. Grey is uniform mix of R, G and B.
    Also, instead of ColorConverOp you may dimply create output image of
    grayscale type and draw your color input image with drawImage().
    If none of these helps please try to provide more details.

  • Sony Image Data Converter no longer opens RAW files

    After upgrading to Snow Leopard Sony Image Data Converter (ver 3.1) cannot open my RAW files. It sees the files but claims they are 0x0 pixels in size. It worked fine with Leopard 10.5.8.

    Image Data Converter v2.2.02 also fails to open any files but was OK in 10.5.8. Image Data Lightbox v1.0.02 does run OK, opens a directory of files fine, and converts them. The app crashes on exit every time however!
    Adobe Camera RAW and Adobe Elements v6 all work perfectly well. But I have never been able to see ARW images in Adobe Bridge!

  • How do i convert an image object to a byte array ?

    Hi
    how do i convert an image object into a byte array
    early reply apperciated

    Oh sorry my method and the other method need to have the pixels from the Image passed to them which you get my using pixelgrabber:
    //create width and height variables from image
              int w = img.getWidth(this);
              int h = img.getHeight(this);
              //retrive picture from image
              int[] pix = new int[w * h];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pix, 0, w);
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              }

  • How to convert an Integer to byte[] without lose data?

    How to convert an Integer to byte[] without lose data?

    I use the following to convert any java Object to a byte array
    public static byte[] getBytes(Object obj) throws java.io.IOException
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            bos.close();
            byte [] data = bos.toByteArray();
            return data;
    }

Maybe you are looking for