How do I read TIFF files in Java 10? - tiff

I tried just doing:
File inputFile = new File("image.tif");
BufferedImage image = ImageIO.read(inputFile);
because I thought Java 10 didn't need extra libraries to handle tiff files but the BufferedImage is null.

Since JDK 9 this should be possible:
private Image readTiffImage() throws IOException
{
final InputStream tiffImage = TiffExample.class.getResourceAsStream("image.tiff");
final BufferedImage bufferedImage = ImageIO.read(tiffImage);
final Image image = SwingFXUtils.toFXImage(bufferedImage, null);
return image;
}

Related

javafx quality of the images uploaded

my application connects to a database in mysql using phpmyadmin and stores an image in the database, but my problem is when I download the image from the database and post the image on a imageview the image has a very low quality where also it's color is being afected too.
if I post the image directly on the database using phpmyadmin and then download the image using my app the image looks fine, but if I upload the image from my app and then i download it then the quality is bad.
the way to post the image is past the image to a byte[] and then uploading to the database that uses the type blob.
private byte[] imagenToByte(Image imagen) {
BufferedImage bufferimage = SwingFXUtils.fromFXImage(imagen, null);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageIO.write(bufferimage, "jpg", output );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data = output.toByteArray();
return data;
}
can you help me please?
EDIT
#FXML
public void eventoBotonSeleccionarImagen() {
FileChooser imagenSeleccionada = new FileChooser();
FileChooser.ExtensionFilter filtroImagenjpg = new ExtensionFilter("Archivos *.jpg", "*.jpg");
FileChooser.ExtensionFilter filtroImagenJPG = new ExtensionFilter("Archivos *.JPG", "*.JPG");
File archivo = imagenSeleccionada.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(archivo);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
imageViewMonstruo.setImage(image);
}
catch(Exception e) {
e.printStackTrace();
}
}
I found the answer to the question thanks to this
this question.
What I've done is changing from Blob to longblob in the database and adding png instead of jpg, the code result is this
private byte[] imagenToByte(Image imagen) {
BufferedImage bufferimage = SwingFXUtils.fromFXImage(imagen, null);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageIO.write(bufferimage, "png", output );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data = output.toByteArray();
return data;
}
And finally it upload and download the images with the same quality

Junit testcase for amazon Rekognition

How can i write a test case in Junit for amazon Rekognition.
public class SearchFaceMatchingImageCollection {
public static final String collectionId = "MyCollection";
public static final String bucket = "bucket";
public static final String photo = "input.jpg";
public static void main(String[] args) throws Exception {
AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
ObjectMapper objectMapper = new ObjectMapper();
// Get an image object from S3 bucket.
Image image=new Image()
.withS3Object(new S3Object()
.withBucket(bucket)
.withName(photo));
// Search collection for faces similar to the largest face in the image.
SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest()
.withCollectionId(collectionId)
.withImage(image)
.withFaceMatchThreshold(70F)
.withMaxFaces(2);
SearchFacesByImageResult searchFacesByImageResult =
rekognitionClient.searchFacesByImage(searchFacesByImageRequest);
System.out.println("Faces matching largest face in image from" + photo);
List < FaceMatch > faceImageMatches = searchFacesByImageResult.getFaceMatches();
for (FaceMatch face: faceImageMatches) {
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(face));
System.out.println();
}
}
}
For the above program I wanted to write a Junit testcase. Kindly help me with the same

Tess4j Image reading

I am using tess4j api for reading an image for numerics.
code as below:
public static void main(String[] args) {
// TODO Auto-generated method stub
final File imageFile = new File("C:\\Users\\goku\\Desktop\\myimage.png");
System.out.println("Image found");
final ITesseract instance = new Tesseract();
instance.setTessVariable("tessedit_char_whitelist", "0123456789");
instance.setDatapath("C:\\Users\\goku\\Downloads\\Tess4J");
instance.setLanguage("eng");
String result;
try {
result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Image attached.
The program is reading the numerics as wrong. Not able to find the issue.
output:
1 1 3 251
regards,
Vasu
Rescaling the image to 300 DPI would get the correct result.
This is how to properly edit image with im4java (imagemagick) so it can be read with tess4j (tesseract):
private static File processImage(File img) throws IOException {
File newImg = File.createTempFile("asdf", ".png");
ImageMagickCmd cmd = new ImageMagickCmd("convert");
IMOperation op = new IMOperation();
op.addImage(img.getAbsolutePath());
op.strip().resample(300).colorspace("gray").autoLevel().threshold(35000).type("bilevel").depth(8).trim();
op.addImage(newImg.getAbsolutePath());
cmd.run(op);
return newImg;
}
It might be the trained data. I have used the trained data from the tesseract-ocr-w64-setup-v4.1.0.20190314.exe Windows binary, found at https://digi.bib.uni-mannheim.de/tesseract/, with the datapath set as below
instance.setDatapath("C:\\Program Files\\Tesseract-OCR\\tessdata");
I do get a warning about the resolution, but the result is correct:
471871882819

Vaadin upload image and store it to database

I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.
Column(name="image")
private byte[] image;
#Lob
#Column(name="image")
private Blob image;
In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:
File file = new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
uIP.uploadImage(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
I tried also this:
byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);
uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array
public void uploadImage(byte[] data) throws SerialException, SQLException{
//Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
showRepo.updateAfterImage(show, data); // or (show, blob)
}
In my repository, in my updateAfterImage method I have:
public void updateAfterImage(Show show, byte[] data) //or Blob data
{
em.getTransaction().begin(); //em - EntityManager
show.setImage(data);
em.getTransaction().commit();
}
Either with Blob or a byte array, I can't manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!
I have found the solution. What made it work was:
em.getTransaction().begin();
em.find(Show.class, show.getId());
show.setImage(data);
em.merge(spectacol);
em.getTransaction().commit();
in my updateAfterImage method in the show repository.

Windows Phone 8.1 Runtime - Image to byte[] and Vice Versa

For my application, I am trying to convert an WriteableBitmap to byte[] to store in the database, and then from byte[] to BitmapImage to display back to the user.
My current methods that so far, produce no results:
public byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
using (Stream stream = bitmap.PixelBuffer.AsStream())
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
To convert from byte array to BitmapImage, I use:
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])buffer);
writer.StoreAsync().GetResults();
}
var image = new BitmapImage();
image.SetSource(ms);
imageByteTest.Source = image;
}
There is good documentation for Silverlight applications I have found, but very little in the way for Windows Store Universal Runtime Applications. Where are these methods going wrong?
You might want to take a look at the WriteableBitmapEx library which contains some extensions to WriteableBitmap, as well as some core features like your conversion of WriteableBitmap to byte array and vice versa.
I wrote a converter for ByteArrayToBitmapImage:
public object Convert(object value, Type targetType, object parameter, string language)
{
var byteArray = value as byte[];
var bitmapImage = new BitmapImage();
Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
using (var stream = new MemoryStream(byteArray))
{
bitmapImage.SetSourceAsync(stream.AsRandomAccessStream());
}
});
return bitmapImage;
}
And byte[] -> WriteableBitmap
public static WriteableBitmap PrepareWritableBitmap(Size size, byte[] pixels)
{
uint height = (uint)Math.Floor(size.Height);
uint width = (uint)Math.Floor(size.Width);
WriteableBitmap bmp = new WriteableBitmap((int)width, (int)height);
Stream pixStream = bmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, (int)(width * height * 4));
//4 is a channel number for RGBA, for RGB is 3 channels
return bmp;
}