OLE object () to ImageIcon using ucanacess - byte

(I am new to java)
I'm trying to extract an OLE object (Picture) 3ºfield of a table "Pessoa" in a MSAcess Database, and put it into an Icon of a JLabel.
But in the line:
ImageIcon ico = new ImageIcon( imagem ) ;
it returns a NullPointerException... And i dont know why...
I've already been reading some articles in here...
Could you help me, please?
Thank's in advance.
public ArrayList<Pessoa> queryPessoa(){
try {
res=sql.executeQuery(qry_pessoa);
posicao=0;
while( res.next() ){
PessoaS.add( new Pessoa( res.getString(1), res.getDate(2).toLocalDate() , res.getBytes(3),res.getString(4),
res.getString(5), res.getDouble(6)));
System.out.printf("\n %s \t %s \t %f \t %s:", PessoaS.get(posicao).getNome() , PessoaS.get(posicao).getApelido(),
PessoaS.get(posicao).getNumero() , PessoaS.get(posicao).getDataNasc().toString() );
JPanel p = new JPanel();
p.setBounds(10,10,800,800);
p.setLayout(null);
InputStream entrada = new ByteArrayInputStream( PessoaS.get(posicao).getFoto() ); //byte[] getFoto();
BufferedImage imagem = ImageIO.read( entrada );
ImageIcon ico = new ImageIcon( imagem ) ;
JLabel r = new JLabel( ico );
r.setBounds(20,20,100,100);
p.add( r );
p.repaint();
p.setVisible(true);
posicao++;
}
}
catch (SQLException sqle){
sqle.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally{ return PessoaS ;}
} ```
In alternative, i tried a more direct approach:
i suppressed the Bufferedimage and the inputStream..now, it doesn't crash, but also doesn't create the Panels whith the Icon labels.
I just want to make a sample example to extract an image...
public ArrayList<Pessoa> queryPessoa(){
try {
res = sql.executeQuery(qry_pessoa);
posicao = 0;
while( res.next() ){
PessoaS.add( new Pessoa( res.getString(1), res.getDate(2).toLocalDate() , res.getBytes(3),res.getString(4),
res.getString(5), res.getDouble(6)));
System.out.printf("\n %s \t %s \t %f \t %s:", PessoaS.get(posicao).getNome() , PessoaS.get(posicao).getApelido(),
PessoaS.get(posicao).getNumero() , PessoaS.get(posicao).getDataNasc().toString() );
JPanel p = new JPanel();
p.setBounds(10,10,800,800);
p.setLayout(null);
JLabel r = new JLabel( new ImageIcon( PessoaS.get(posicao).getFoto() ) );
r.setBounds(20,20,100,100);
p.add( r );
p.repaint();
p.setVisible(true);
posicao++;
}
}
catch ( SQLException sqle){
sqle.printStackTrace();
}
catch ( Exception e){
e.printStackTrace();
}
finally{ return PessoaS ;}
}

Related

Xamarin.Forms Android save image to gallery

I have a stream which is the result of taking a photo. I want to save that photo to the users Gallery.
I have tried all manner of things but nothing takes... The class I am saving is a plain C# class - it does not inherit form any android types but that could be done if necessary (to fire an intent perhaps - though I tried this and it ended up another rabbit hole)
I have tried this:
try{
using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + _name, FileMode.OpenOrCreate))
{
fs.Write(bytes, 0, bytes.Length);
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
and also:
if (_filename.ToLower ().Contains (".jpg") || _filename.ToLower ().Contains (".png")) {
stream.Position = 0;
var bitmap = BitmapFactory.DecodeStream (stream);
var finalStream = new MemoryStream ();
bitmap.Compress (Bitmap.CompressFormat.Jpeg, 25, finalStream);
bitmap = null;
finalStream.Position = 0;
var path2 = Environment.GetFolderPath (Environment.SpecialFolder.MyPictures);
var filename2 = System.IO.Path.Combine (path2, _filename);
using (var fileStream = File.Create (filename2)) {
finalStream.Seek (0, SeekOrigin.Begin);
finalStream.CopyTo (fileStream);
fileStream.Close ();
finalStream.Dispose ();
stream.Dispose ();
fileStream.Dispose ();
GC.Collect ();
}
return;
}
I thought this would be an easy task! meh...
Any help?
Use the MediaStore ContentProvider. MediaStore.Images.Media has several Insert methods you can use to add content to the gallery.

ABCPDF 8 - How do I create a layered PDF

I need to use ABCPDF to create a layered PDF file. I've seen examples for watermarks but I need to have a PDF be the second layer. My code is below. When I run it, I only see one layer. What am I doing incorrectly?
Thank you.
WebSupergoo.ABCpdf8.Doc artworkDoc = new WebSupergoo.ABCpdf8.Doc();
artworkDoc.SetInfo(0, "License", _License);
WebSupergoo.ABCpdf8.Doc cutDoc = new WebSupergoo.ABCpdf8.Doc();
cutDoc.SetInfo(0, "License", _License);
// Attempt to read in Artwork File
try
{
artworkDoc.Read(ArtworkPath);
}
catch (Exception ex)
{
Exception noartwork = new Exception("Problem with Artwork File: " + ex.ToString());
throw noartwork;
}
// Attempt to read in cut File
try
{
cutDoc.Read(cutPath);
}
catch (Exception ex)
{
Exception nocut = new Exception("Problem with cut File: " + ex.ToString());
throw nocut;
}
WebSupergoo.ABCpdf8.Doc outputDoc = artworkDoc;
outputDoc.SetInfo(0, "License", _License);
// Attempt to merge artwork and cut files into output Document
try
{
outputDoc.PageNumber = 1;
outputDoc.Layer = outputDoc.LayerCount + 1;
outputDoc.AddImageDoc(cutDoc, 1, outputDoc.Rect);
}
catch (Exception ex)
{
Exception problem = new Exception("Problem appending cut and artwork files to output: " + ex.ToString());
throw problem;
}
// Attempt to save the output Document to the specified output path
try
{
outputDoc.Save(OutputPath);
artworkDoc.Clear();
cutDoc.Clear();
outputDoc.Clear();
}
catch (Exception ex)
{
Exception invalidOutput = new Exception("Unable to write output file: " + ex.ToString());
throw invalidOutput;
}
return true;
}
After resorting to using iTextSharp for some other PDF layer issues I had, I decided to explore how to use iTextSharp to create a new layered PDF file where the layers are pages from existing PDF files. The below code is what I came up with. The code presumes each of the source PDF files only has one page to add as a layer to the new PDF. It took me awhile to figure out so hopefully posting it here will help save others some time.
try
{
iTextSharp.text.pdf.PdfReader artwork = new iTextSharp.text.pdf.PdfReader(#”c:\artwork.pdf”);
iTextSharp.text.pdf.PdfReader cut = new iTextSharp.text.pdf.PdfReader(#”c:\cut.pdf”);
//get size of the cut PDF so the new layered PDF will be sized the same.
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(cut.GetPageSize(1).Width, cut.GetPageSize(1).Height);
//the artwork PDF needs to be sized the same as the cut pdf
if (artwork.GetPageSize(1).Width != pageSize.Width || artwork.GetPageSize(1).Height != pageSize.Height)
{
string resizedFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(textBox1.Text),System.IO.Path.GetFileNameWithoutExtension(textBox1.Text) + "_resized.pdf");
iTextSharp.text.Document resizedArtwork = new iTextSharp.text.Document(pageSize);
iTextSharp.text.pdf.PdfWriter resizedWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(resizedArtwork, new System.IO.FileStream(resizedFile, System.IO.FileMode.Create));
iTextSharp.text.pdf.PdfImportedPage importedPage = resizedWriter.GetImportedPage(artwork, 1);
resizedArtwork.Open();
iTextSharp.text.pdf.PdfContentByte resizedContentByte = resizedWriter.DirectContent;
resizedContentByte.AddTemplate(importedPage, 0, 0);
resizedArtwork.Close();
//close reader associated with non-resized document
artwork.Close();
//set reader to resized document
artwork = new iTextSharp.text.pdf.PdfReader(resizedFile);
}
//create a new PDF
string outputFileName = #”c:\layered.pdf”;
iTextSharp.text.Document newPDF = new iTextSharp.text.Document(pageSize);
//create writer to output new PDF's contents to
iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newPDF, new System.IO.FileStream(outputFileName,System.IO.FileMode.Create));
//grab the first page from the artwork and cut PDF. These will become new layers in the new PDF
iTextSharp.text.pdf.PdfImportedPage artworkImportedPage = pdfWriter.GetImportedPage(artwork, 1);
iTextSharp.text.pdf.PdfImportedPage cutImportedPage = pdfWriter.GetImportedPage(cut, 1);
newPDF.Open();
iTextSharp.text.pdf.PdfContentByte pdfContentByte = pdfWriter.DirectContent;
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("artwork",pdfWriter));
pdfContentByte.AddTemplate(artworkImportedPage, 0, 0);
pdfContentByte.EndLayer();
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("cut", pdfWriter));
pdfContentByte.AddTemplate(cutImportedPage, 0, 0);
pdfContentByte.EndLayer();
newPDF.Close();
pdfWriter.Close();
artwork.Close();
cut.Close();
}
catch (Exception ex)
{
}

javacv: grabber.getFrameRate() return 0

I have used javacv for my project to deal with avi.
The video shows faster than normal, I want to get the fps to set the speed of the video. But grabber.getFrameRate() return 0, as the same with grabber.getLengthInFrames() and grabber.getSampleRate(), can anyone tell me why?
code snippet below:
FrameGrabber grabber = new OpenCVFrameGrabber("sample.avi");
double fps=grabber.getFrameRate();
System.out.println(fps);
//int n=grabber.getLengthInFrames();
//int f=grabber.getSampleRate();
CvMemStorage storage = CvMemStorage.create();
grabber.start();
grabbedImage = grabber.grab();
while (frame.isVisible() && (grabbedImage = grabber.grab()) != null)
{
BufferedImage bfimg = grabbedImage.getBufferedImage();
frame.showImage(bfimg);
frame.waitKey((int)(1000/fps));
cvClearMemStorage(storage);
}
grabber.stop();
you must call after start();
maybe you can
FrameGrabber grabber = new OpenCVFrameGrabber("sample.avi");
grabber.start();
double fps=grabber.getFrameRate();
I use this code to record mp4 video:
public static void main(String[] args) {
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
try {
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start();
IplImage grabbedImage = grabber.grab();
canvas.setCanvasSize(grabbedImage.width(), grabbedImage.height());
System.out.println("framerate = " + grabber.getFrameRate());
grabber.setFrameRate(grabber.getFrameRate());
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("c:/demo.mp4", 320, 240);
recorder.setVideoCodec(13);
recorder.setFormat("mp4");
recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
recorder.setFrameRate(10);
recorder.setVideoBitrate(5*1024);
recorder.start();
System.out.println("framerate = " + grabber.getFrameRate());
while (canvas.isVisible() && (grabbedImage = grabber.grab()) != null) {
canvas.showImage(grabbedImage);
recorder.record(grabbedImage);
}
recorder.stop();
grabber.stop();
canvas.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
I tried this in a webcam example and it worked:
double time1,time2;
// your loop
while(....){
time1=System.currentTimeMillis(); // add this first in the loop
//code here
.
.
.
.
time2=System.currentTimeMillis(); // add this at the end of the loop
System.out.println("framerate = " + 1/(((time2-time)/1000)%60))
} //end of loop
In case of webcam example with code for webcam found:
http://opencvlover.blogspot.com/2012/05/accessing-webcam-using-javacv.html
it looks like this :
IplImage img
while (...) {
time1=System.currentTimeMillis(); // add this first in the loop
//inser grabed video fram to IplImage img
img = grabber.grab();
.
.
.
.
//Show video frame in canvas
canvas.showImage(img);
time2=System.currentTimeMillis(); // add this at the end of the loop
System.out.println("framerate = " + 1/(((time2-time)/1000)%60))
} //end of loop
.
.
.

Image overlay with camera captured image in android

I need to take a picture with the camera and at the same time show an overlay image on top of the camera view. After the picture is taken, i need to save what the user saw while taking the picture. Can anyone suggest me? Please.
public void onPictureTaken(byte[] data, Camera camera){
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
wid = cameraBitmap.getWidth();
hgt = cameraBitmap.getHeight();
Bitmap newImage = Bitmap.createBitmap(wid , hgt , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newImage);
canvas.drawBitmap(cameraBitmap, 0f, 0f, null);
Drawable drawable = getResources().getDrawable(R.drawable.d);
drawable.setBounds(20 ,20, 260, 160);
drawable.draw(canvas);
File storagePath = new File(Environment.getExternalStorageDirectory() + "/Vampire Photos/");
storagePath.mkdirs();
File myImage = new File(storagePath,Long.toString(System.currentTimeMillis()) + ".jpg");
try
{
FileOutputStream out = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch(FileNotFoundException e)
{
Log.d("In Saving File", e + "");
}
catch(IOException e)
{
Log.d("In Saving File", e + "");
}
camera.startPreview();
drawable = null;
newImage.recycle();
newImage = null;
cameraBitmap.recycle();
cameraBitmap = null;
} };

Why is part of the image cut out when taking a picture with this code on Blackberry?

When I take a picture on the simulator (Haven't tried a device yet) the result is only less than half of the image and the rest is gray. Does anyone know why?
Thanks
listener = new FileSystemJournalListener()
{
private long _lastUSN;
public void fileJournalChanged()
{
long nextUSN = FileSystemJournal.getNextUSN();
FileSystemJournalEntry entry = FileSystemJournal.getEntry(nextUSN - 1);
nextUSN++;
switch (entry.getEvent()) {
case FileSystemJournalEntry.FILE_ADDED:
try
{
FileConnection fconn = (FileConnection)Connector.open("file://" +entry.getPath());
if(fconn.exists())
{
InputStream input = null;
input = fconn.openInputStream();
byte[] data = new byte[(int) fconn.fileSize() + 1000];
input.read(data);
rawImage = data;
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
if(input != null)
{
input.close();
}
Bitmap[] images = new Bitmap[1];
images[0] = pic;
//labels[1] = "Label for image 2";
// tooltips[1] = "Tooltip for image 2";
// labels[2] = "Label for image 2";
// tooltips[2] = "Tooltip for image 2";
ScrollEntry[] entries = new ScrollEntry[images.length];
entries[0] = new ScrollEntry(images[0], "", "");
PictureScrollField pictureScrollField = new PictureScrollField(175, 131);
pictureScrollField.setData(entries, 0);
pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE_WITH_SHRINK_LENS);
// pictureScrollField.setHighlightBorderColor(Color.BLUE);
pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 150));
insert(pictureScrollField, 1);
picTaken = true;
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 50);
inject.post();
inject.post();
}
break;
}
catch (Exception e)
{
// TODO Auto-generated catch block
Dialog.alert(e.toString());
}
//either a picture was taken or a picture was added to the BlackBerry device
case FileSystemJournalEntry.FILE_DELETED:
//a picture was removed from the BlackBerry device;
break;
}
input.read(data) only reads some amount of data, not all of it. If you want to read the whole file, use IOUtilities.streamToBytes(input); instead, like this:
byte[] data = IOUtilities.streamToBytes(input);
byte[] data = new byte[(int) fconn.fileSize() + 1000];
...
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
I think data now contains last wrong 1000 bytes, try changing to:
byte[] data = new byte[(int) fconn.fileSize()];
I faced the same problem. Just use:
synchronized(UiApplication.getEventLock()) {
//your code here
}

Resources