How can I construct bitmap from Byte Array - blackberry

I need to read image from url then I have to set it as background of page ,so i need to construct Bitmap from byte array ,how can i do this?

private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}

Just import RIM library:
import net.rim.device.api.system.Bitmap;
And use the function:
Bitmap bitmap = Bitmap.createBitmapFromBytes(bytesArray, 0, bytesArray.length, 1);
Where bytesArray is your byte[] data

Related

base64 string to image returns only single image in C# MVC

I Am getting Images from Reporting service engine in terms of byte array.
byte[] imageBytes = Convert.FromBase64String(base64);//base64 is an byte array
I am converting this byte array to to image
MemoryStream ms1 = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms1.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image images = System.Drawing.Image.FromStream(ms1, true);**
But when I save it it stores only first image
images.Save(Server.MapPath("~/img.png"),System.Drawing.Imaging.ImageFormat.Png);
it must save two images.I am not able to detect base64 first image or second image
You're only saving a single image from that byte array. PNGs don't contain multiple images, so you would have to know where to "split" the base64 so you get two images. See the pseudocode below to get an idea of what I am saying:
int i = 1;
string split = "//**//";
// the string "//**//" was inserted so we know where to split the string to
// extract mutiple images. It can be any string value
foreach (var b64str in base64.Split(split))
{
byte[] imageBytes = Convert.FromBase64String(b64str);//base64 is an byte array
MemoryStream ms1 = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms1.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image images = System.Drawing.Image.FromStream(ms1, true);
images.Save(Server.MapPath("~/img" + i.ToString() + ".png"),System.Drawing.Imaging.ImageFormat.Png);
i++;
}
I solved issue from this URL How to show multi paged image in <img/> tag?
At bottom of page they provide solution working fine....
First- Get all the frames from the stream of image as list of Images
public List<Image> GetAllFrames(Stream sm)
{
List<Image> images = new List<Image>();
Bitmap bitmap = new Bitmap(sm);
int count = bitmap.GetFrameCount(FrameDimension.Page);
for (int idx = 0; idx < count; idx++)
{
bitmap.SelectActiveFrame(FrameDimension.Page, idx);
MemoryStream byteStream = new MemoryStream();
bitmap.Save(byteStream, ImageFormat.Tiff);
images.Add(Image.FromStream(byteStream));
}
return images;
}
Second - Combine all frames in to a single bitmap.
public Bitmap CombineAllFrames(List<Image> test)
{
int width = 0;
int height = 0;
Bitmap finalImage = null;
try
{
foreach (Bitmap bitMap in test)
{
height += bitMap.Height;
width = bitMap.Width > width ? bitMap.Width : width;
}
finalImage = new Bitmap(width, height);
using (System.Drawing.Graphics gc = Graphics.FromImage(finalImage))
{
gc.Clear(Color.White);
int offset = 0;
foreach (Bitmap bitmap in test)
{
gc.DrawImage(bitmap, new Rectangle(0, offset, bitmap.Width, bitmap.Height));
offset += bitmap.Width;
}
}
}
catch (Exception)
{
throw;
}
return finalImage;
}
This methods creates a bitmap which will append all the frames into single one vertically. If you want it horizontally make update it to
width += bitmap.Width;
height = bitmap.Height > height ? bitmap.Height : height;
g.DrawImage(image, new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
Third step - Now if you want a byte array for the created image call the below method
public byte[] GetBytesFromImage(Bitmap finalImage)
{
ImageConverter convertor = new ImageConverter();
return (byte[])convertor.ConvertTo(finalImage, typeof(byte[]));
}

CascadeClassifier in java does not find face with webcam

I am trying to translate the OpenCV CascadeClassifier tutorial from C++ to Java. Working good in C++. Also this java tutorial is working fine.
But the translation is simply not detecting the face. I don't get explicit errors. I can see the processing of the video input from the webcam (grey/histogram...) and the video display. Cascade load doesn't give error. But the CascadeClassifier call just doesn't return any faces... So, you probably can skip all the code and just go to my CascadeClassifier call, down to public Mat detect(Mat inputframe). As I am new to Java and OpenCV, I paste the rest (I removed anything I felt may not be significant), just in case, but don't mean for you to debug that...
I have also tried this call (and other portions) in many different ways and nothing... running out of ideas...
Thank you!!
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
class My_Panel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage image;
private CascadeClassifier face_cascade;
// Create a constructor method
public My_Panel(){
super();
String face_cascade_name = "/haarcascade_frontalface_alt.xml";
//String face_cascade_name = "/lbpcascade_frontalface.xml";
//-- 1. Load the cascades
String str;
str = getClass().getResource(face_cascade_name).getPath();
str = str.replace("/C:","C:");
face_cascade_name=str;
face_cascade=new CascadeClassifier(face_cascade_name);
if( !face_cascade.empty())
{
System.out.println("--(!)Error loading A\n");
return;
}
else
{
System.out.println("Face classifier loooaaaaaded up");
}
}
private BufferedImage getimage(){
return image;
}
public void setimage(BufferedImage newimage){
image=newimage;
return;
}
/**
* Converts/writes a Mat into a BufferedImage.
*
* #param matrix Mat of type CV_8UC3 or CV_8UC1
* #return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
*/
public BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int)matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for(int i=0; i<data.length; i=i+3) {
b = data[i];
data[i] = data[i+2];
data[i+2] = b;
}
break;
default:
return null;
}
BufferedImage image2 = new BufferedImage(cols, rows, type);
image2.getRaster().setDataElements(0, 0, cols, rows, data);
return image2;
}
public void paintComponent(Graphics g){
BufferedImage temp=getimage();
g.drawImage(temp,10,10,temp.getWidth(),temp.getHeight(), this);
}
public Mat detect(Mat inputframe){
Mat mRgba=new Mat();
Mat mGrey=new Mat();
MatOfRect faces = new MatOfRect();
//MatOfRect eyes = new MatOfRect();
inputframe.copyTo(mRgba);
inputframe.copyTo(mGrey);
Imgproc.cvtColor( mRgba, mGrey, Imgproc.COLOR_BGR2GRAY);
Imgproc.equalizeHist( mGrey, mGrey );
face_cascade.detectMultiScale(mGrey, faces);
//face_cascade.detectMultiScale(mGrey, faces, 1.1, 2, 0|Objdetect.CASCADE_SCALE_IMAGE, new Size(30, 30), new Size(200,200) );
//face_cascade.detectMultiScale(mGrey, faces, 1.1, 2, 2//CV_HAAR_SCALE_IMAGE,
// ,new Size(30, 30), new Size(200,200) );
System.out.println(String.format("Detected %s faces", faces.toArray().length));
return mGrey;
}
}
public class window {
public static void main(String arg[]){
// Load the native library.
System.loadLibrary("opencv_java245");
String window_name = "Capture - Face detection";
JFrame frame = new JFrame(window_name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
My_Panel my_panel = new My_Panel();
frame.setContentPane(my_panel);
frame.setVisible(true);
//-- 2. Read the video stream
BufferedImage temp;
Mat webcam_image=new Mat();
VideoCapture capture =new VideoCapture(0);
if( capture.isOpened())
{
while( true )
{
capture.read(webcam_image);
if( !webcam_image.empty() )
{
frame.setSize(webcam_image.width()+40,webcam_image.height()+60);
//-- 3. Apply the classifier to the captured image
// At this point I was wondering where this should be done.
// I put it within the panel class, but maybe one could actually
// create a processor object...
webcam_image=my_panel.detect(webcam_image);
//-- 4. Display the image
temp=my_panel.matToBufferedImage(webcam_image);
my_panel.setimage(temp);
my_panel.repaint();
}
else
{
System.out.println(" --(!) No captured frame -- Break!");
break;
}
}
}
return;
}
}
PS.: Other info, just in case:
mGrey is: Mat [ 480*640*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x19d9af48, dataAddr=0x19dc3430 ]
face is: Mat [ 0*0*CV_8UC1, isCont=false, isSubmat=false, nativeObj=0x194bb048, dataAddr=0x0 ]
I have tried your code and it works fine! You have only one issue with haarcascade_frontalface_alt.xml file location. Try to use a full path to the file:
face_cascade= new CascadeClassifier("D:/HelloCV/src/haarcascade_frontalface_alt.xml");

iOS deve with Starling framework: take a screenshot and save it to the camera roll

I use flash for ios development and I use starling framework.
I'm trying to take a screenshot and then save it to the camera roll, but cameraRoll only accepts bitmapdata. How am I going to convert sprite to bitmapdata? Thanks a million!!
You can convert Sprite to BitmapData using BitmapData.draw() method.
Here's an example.
Try to get an byte array for this use can use Encoder like JPGEncoder or PNGEncoder from byte array you can easily convert to bitmapData.
And the code which i used for converting byte array to bitmapData is here. I hope it would be helpfull for you.If you send any byteArray by calling this class it would convert you bitmapData and return back using callBack Function.
package browsingImages
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.ByteArray;
import scenes.Subscenes.KeepDiary;
public class BitmapDataConverter
{
// private var _KeepDiary:KeepDiary;
private var bmpData:BitmapData;
private var _loader:Loader;
private var _callB:Function;
public function BitmapDataConverter(byteArr:ByteArray,callB:Function)
{
_callB=callB;
getBitmapFunc(byteArr);
}
private function getBitmapFunc(bytArr:ByteArray):void{
if(bytArr != null){
bmpData = new BitmapData(100, 100, true,0xFFFFFF);
_loader = new Loader();
_loader.loadBytes(bytArr);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderAdded);
}
}
private function onLoaderAdded(eve:Event):void{
_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderAdded);
bmpData.draw(_loader);
bmpData = Bitmap(_loader.content).bitmapData;
if(_callB != null)
_callB(bmpData);
}
}
}
Actually, you cant use draw for starling's Sprite.
this code works for me:
public static function copyAsBitmapData(displayObject:DisplayObject, transparentBackground:Boolean = true, backgroundColor:uint = 0xcccccc):BitmapData
{
if (displayObject == null || isNaN(displayObject.width)|| isNaN(displayObject.height))
return null;
var resultRect:Rectangle = new Rectangle();
displayObject.getBounds(displayObject, resultRect);
var result:BitmapData = new BitmapData(displayObject.width, displayObject.height, transparentBackground, backgroundColor);
var context:Context3D = Starling.context;
var support:RenderSupport = new RenderSupport();
RenderSupport.clear();
support.setOrthographicProjection(0, 0, Starling.current.stage.stageWidth, Starling.current.stage.stageHeight);
support.applyBlendMode(true);
support.translateMatrix( -resultRect.x, -resultRect.y);
support.pushMatrix();
support.blendMode = displayObject.blendMode;
displayObject.render(support, 1.0);
support.popMatrix();
support.finishQuadBatch();
context.drawToBitmapData(result);
return result;
}

ActionScript 3.0: How to convert JPEG-encoded ByteArray to Bitmap

ActionScript 3.0: How to convert JPEG-encoded ByteArray to Bitmap
The JPEGEncoder class can convert the raw bitmapdata into JPEG-encoded ByteArray Object, and I just want to know how to do the other way around.
As I know, you can do it simply using Loader.loadBytes:
private var loader:Loader = new Loader();
private function convertByteArray(ba:ByteArray):void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.loadBytes(ba);
}
private function completeHandler(event:Event):void
{
var bitmap:Bitmap = Bitmap(loader.content);
}

(WP7.5)e.ChosenPhoto issue

my code are as follows
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Stream stream = e.ChosenPhoto;
int len = (int)stream.Length;
byte[] PhoteBytes = new byte[len];
stream.Read(PhoteBytes,0,len);
}
}
I am wondering is it possible to convert
byte array(PhoteBytes in this example)
to WriteableBitmap?
Thanks for the help
Try this.
WritableBitmap bitmap = new WritableBitmap(); //Use appropriate constructor
bitmap.SetSource(e.ChosenPhoto);
EDIT: You'll have to use the appropriate constructor. In one WriteableBitmap(Int32, Int32) constructor you can specify the bitmap width and height. See documentation here

Resources