Convert Blob to JPG and update blob - java

I'm trying to read in a blob, convert it to JPG and then write back to the blob (it is being passed in by reference, but when trying to compile in TOAD I get an error on ImageIO.write.
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED BANNADMIN.IMAGE_CONVERTER
AS package uk.co.ImageUtil;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import oracle.sql.*;
import java.io.OutputStream;
public class ImageConverter {
public static void convertImage(BLOB[] blob) {
BufferedImage image = null;
OutputStream outputStream = null;
try {
image = ImageIO.read(blob[0].getBinaryStream());
outputStream = blob[0].setBinaryStream(0);
ImageIO.write(image, "JPG", outputStream);
} catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch(IllegalArgumentException e) {
e.printStackTrace();
}
finally {
try {
if (outputStream !== null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/
How would I convert a BufferedImage into a RenderedImage so I can write the JPG version back into the Blob?
Update: The error message is
[Error] (1: 0): IMAGE_CONVERTER:28: cannot find symbol
[Error] (1: 0): symbol : method write(java.awt.image.BufferedImage,java.lang.String,java.lang.Object)
[Error] (1: 0): location: class javax.imageio.ImageIO
[Error] (1: 0): ImageIO.write(image, "jpg", outputStream);
[Error] (1: 0): ^
[Error] (1: 0): 1 error

Turned out it was a simple mistake, ImageIO.write takes in a RenderedImage which meant I had to cast the BufferedImage to RenderedImage, and I had written !== instead of != in the finally block. See below for what compiles successfully
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED BANNADMIN.IMAGE_CONVERTER AS package uk.co.ImageUtil;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import oracle.sql.*;
import java.io.OutputStream;
import java.sql.SQLException;
public class ImageConverter {
/**
* Take in a BLOB file (specified as an array parameter but we only ever use [0])
* Read in the binary stream of the BLOB
* Change the binary stream to jpg
* Write the binary stream jpg to the BLOB
* The BLOB parameter is passed in via out - so there is no need to return the BLOB, only edit it
*/
public static void convertImage(BLOB[] blob) {
BufferedImage bufferedImage = null;
OutputStream outputStream = null;
try {
bufferedImage = ImageIO.read(blob[0].getBinaryStream());
outputStream = blob[0].setBinaryStream(0);
RenderedImage renderedImage = (RenderedImage)bufferedImage;
ImageIO.write(renderedImage, "JPG", outputStream);
} catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch(IllegalArgumentException e) {
e.printStackTrace();
}
finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/

Related

Convert text file data into uppercase in Java

I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

accessing a local file (Java URL)

I'm trying to open a stream to a file on my PC and I'm trying to do it via URL (I know,It's just for leraning purposes)
this is what I'm doing:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
public class URLTyper {
public static void main(String[] args) {
InputStream in=null;
try {
URL url=new URL("file://127.0.0.1/c:/haxlogs.txt");
// in=url.openStream();
URLConnection conn=url.openConnection();
conn.connect();
in=conn.getInputStream();
while (true) {
int read=in.read();
if (read==-1) break;
System.out.write(read);
}
}
catch (SocketTimeoutException e){
System.out.println("timed out");
}
catch (MalformedURLException e) {
System.out.println("URL not valid");
}
catch (IOException e) {
System.out.println("unable to get data");
}
}
}
It exits throwing an IOException ("unable to access data").. why is it not working? shouldn't it get to the file like an ordinary InputStream?
thanks

Method for FileUpload throwing errors in Java-Windows

I want to test one sample program for file Uploading.But it is showing error "FileNotFoundException".
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestUpload {
/**
* #param args
*/
public boolean handleFileUpload(){
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
boolean isFileUplodedCorrectly = true;
try {
bos = new BufferedOutputStream(new FileOutputStream(new File("D:\\vishu.jpeg")));
bis = new BufferedInputStream(new FileInputStream(new File("D:\\vishuGreetings.jpeg")));
byte[] b = new byte[1024];
while (bis.read(b) != -1)
bos.write(b);
bos.flush();
} catch (Exception e) {
isFileUplodedCorrectly = false;
e.printStackTrace();
System.out.print("Exception in FileUpload Utils " + e);
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return isFileUplodedCorrectly;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestUpload tu=new TestUpload();
System.out.println("Status"+tu.handleFileUpload());
}
}
Actually the file is present there. Please Check.
java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at TestUpload.handleFileUpload(TestUpload.java:23)
at TestUpload.main(TestUpload.java:52)
Exception in FileUpload Utils java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)Statusfalse
The file D:/vishuGreetings.jpeg is present there.But I am getting a File Not Found Exception for the same.Please check the code provided and revert back.
I solved the problem by giving .jpg instead of jpeg and found it working fine.When I check the properties of the file it is jpeg. that is why I used the extension jpeg in the file nmae in the code.Sorry for the trouble.

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Saving to binary/serialization java

I have to, quote on quote,
1.Save accounts to a binary (serialized) file.
2.Load (recreate) accounts from a binary (serialized) file.
So firstly, I was looking up examples of what exactly that is and I am lost, in same scenarios people mention xml, in my head I think it means like 01010011000 (binary), and when I look at other code it looks like a normal text file save.
What exactly does he mean, and can someone post an example, or give me a site that better clarifies this?
Once I see what I actually need to do, I can implement it easily, I'm just confused on what exactly is being saved (data-wise) and how.
*I already have an option to save via textfile (.txt) if I can just use some of that code for this binary part.
Thanks!
Here is what I have now, it's still not working I think.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SerializationMain implements Serializable {
public static void saveSerialized(Object YourObject, String filePath) throws IOException {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(filePath + ".dat"));
outputStream.writeObject(YourObject);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static Object loadSerialized(String filePath, Object[][] data1) throws IOException {
try {
FileInputStream fileIn = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
try {
data1 = (Object[][]) in.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SerializationMain.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(data1.length);
return data1;
}
}
Assuming you have a class called "account" you simply need to implements Serializable at the top of your class header.
From my understanding, that will serialize all the data into a binary form. You will need to of course still perform the steps to actually write/read the class object out to a file using ObjectOutputStream/ObjectInputStream.
So for example...
public class account implements Serializable
{ ...
}
Then in your main function for example, where you want to save the object, you would create a File, attach it to an ObjectOutputStream and write out your object in binary form.
First hit on google: http://www.javacoffeebreak.com/articles/serialization/index.html - basically you should serialize your object to a file. Then you can load it into an object again later.

Categories