I know this seems like a common question but i have looked all over the internets, and tried many different tutorials and methods for doing this. I think i am close, but not sure. Also i am using Play Framework but it should be the same for java. here is my error
javax.image.IIOException: I/O error reading PNG header!
at com.sun.plugins.png.PNGImageReader.readHeader(Unknown Source)
...
...
Caused by: java.io.EOFException
at javax.imageio.stream.ImageInputStreamImpl.readFully(Unknown Source)
...
Here is my code where i get the picture among other things from a form and convert the image to a byte[] and store in MS SQL db.
@Transactional
public static Result submitTrailer(){
filledForm = newTrailerForm.bindFromRequest();
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture = body.getFile("file");
String fileName = picture.getFilename();
System.out.println(fileName);
String contentType = picture.getContentType();
System.out.println(contentType);
final File file = picture.getFile();
filledForm.get().setContentType(contentType);
try{
BufferedImage originalImage = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, contentType, baos);
filledForm.get().setImage(baos.toByteArray());
baos.flush();
baos.close();
filledForm.get().save();
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.index.index.render());
}
here is where i am trying to covert the byte[] back to an image so i can display it in html
public File getConvertedPicture(){
File imageFile;
System.out.println("byteToImage() called");
if(getImage()==null){
System.out.println("getByteImage()==null");
return null;
}else{
try{
ByteArrayInputStream bis = new ByteArrayInputStream(getImage());
imageFile=File.createTempFile("pattern", ".suffix");
Iterator<?> readers = ImageIO.getImageReadersByFormatName("PNG");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
ImageIO.write(bufferedImage,"PNG", imageFile);
return imageFile;
}
catch(IOException e){
e.printStackTrace();
return null;
}
}
I am a beginner, this is my first time using play, and first time using databases. Any advice to get this to work would be greatly appreciated.
also, in my method getConvertedPicture() i have to specify the format type, is there anyway to get around this so the user can upload any type of picture they want.