how to convert JPEG image to TIFF image? - java

I am developing an app for image processing for that I need to convert JPEG file to TIFF file.
I have tried below code snippet for conversion. But, it is generating corrupt tiff file.
Here is the code:
package javaapplication2;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.idrsolutions.image.tiff.TiffEncoder;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class JavaApplication2
{
public static void main(String[] args)
{
BufferedImage bufferedImage;
try
{
bufferedImage = ImageIO.read(new File("C:\\Users\\Jay Tanna\\Desktop\\image1.jpg"));
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
OutputStream out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");
TiffEncoder tiffEncoder = new TiffEncoder();
tiffEncoder.setCompressed(true);
tiffEncoder.write(newBufferedImage, out);
System.out.println("Done");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Kindly help me with this issue.

Not familiar with com.idrsolutions.image.tiff.TiffEncoder, but you're definitely missing a out.close() without which some data may remain buffered and not make it to disk.

Change the extension of the file, try this:
OutputStream out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.tiff");
for this:
OutputStream out = new FileOutputStream("C:\\Users\\Jay Tanna\\Desktop\\myNew_File.TIF");

Related

Cannot save filtered image to external storage android

I am not a Java guy at all.
While using react-native-vision-camera, I need to create my own frame processor. This frame processor will simply apply some opengl filter on each frame and return the path where the filtered image is saved. This is what I have written so far, most of them is copied from here and there to fit my need.
package com.story;
import android.util.*;
import android.content.Context;
import android.os.Environment;
import java.lang.String;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.lang.System;
import java.lang.StringBuilder;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.*;
import java.text.SimpleDateFormat;
import androidx.camera.core.ImageProxy;
import android.media.Image;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.wysaid.common.Common;
import org.wysaid.common.SharedContext;
import org.wysaid.myUtils.FileUtil;
import org.wysaid.myUtils.ImageUtil;
import org.wysaid.myUtils.MsgUtil;
import org.wysaid.nativePort.CGEImageHandler;
import org.wysaid.nativePort.CGENativeLibrary;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.mrousavy.camera.frameprocessor.FrameProcessorPlugin;
import org.jetbrains.annotations.NotNull;
public class FrameEffectPlugin extends FrameProcessorPlugin {
public static String status = "";
private Bitmap convertImageProxyToBitmap(ImageProxy image) {
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);
}
public String saveBitmap(Bitmap finalBitmap, String fname) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cache-images");
if(!myDir.exists() || !myDir.isDirectory()){
myDir.mkdirs();
}
File file = new File(myDir, fname);
if (file.exists()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
status = "exception while saving bitmap";
e.printStackTrace();
}
return file.getAbsolutePath();
}
#Override
public Object callback(#NotNull ImageProxy image, Object[] params) {
Bitmap bitmapImg = convertImageProxyToBitmap(image);
String ruleString = "#adjust hsl 0.02 -0.31 -0.17";
Bitmap dstImage = CGENativeLibrary.filterImage_MultipleEffects(bitmapImg, ruleString, 1.0f);
String timeStamp = System.currentTimeMillis() + "";
String fname = "storyCache_"+ timeStamp +".jpg";
String path = saveBitmap(dstImage, fname);
WritableNativeMap map = new WritableNativeMap();
map.putString("path", path);
map.putString("status", status);
return map;
}
FrameEffectPlugin() {
super("addFrameEffect");
}
}
It always says exception while saving bitmap as status. If I try to render the image in react native with the path returned, it doesn't show anything(which should actually happen).
At this point, I think the problem is happening from convertImageProxyToBitmap() function. It is being unable to produce a Bitmap so the library(gpuimage-plus) is unable to apply filters. So, the image is not being saved.
But I am a noob in this field so I don't have any idea what to fix/to do next. Please help me to solve this :(

Problem with colors after converting image

I have a class which converts images from PNG to JPG (for space saving reasons). My problem is that most of images goes form this to this. [
Currently I found only two pictures that are not affected by conversion gallery but if you're using default windows 10 pictures app windows ignores them when going through pictures. If I open them app behaves like this is only picture in folder even if this isn't true.
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
public class PNG2JPG {
boolean status;
PNG2JPG(String path,float quality){
File file = new File(path);
try {
BufferedImage image = ImageIO.read(file);
String fileName = file.getName();
path = path.substring(0,path.lastIndexOf('\\'));
fileName = fileName.substring(0,fileName.lastIndexOf('.'));
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality); //Quality from 0 to 1
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(new FileImageOutputStream(
new File(path + "/" + fileName + ".jpg")));
writer.write(null, new IIOImage(image, null, null), jpegParams);
status = true;
}
catch (IOException e){
System.out.println("No file found");
status = false;
}
}
}

Google zxing api unable to decode barcode

I am using google zxing api for java to decode a barcode png image.The code is as below.The function new MultiFormatReader().decode(bitmap).getText()) does not work properly for all the barcode images.Please let me know in case any other additional details are required and if there's any better way to decode barcode images using google zxing.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.codec.BinaryDecoder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
public class DecodeBarcode {
public static void main(String[] args) throws IOException {
BufferedImage qrCodeImage = null;
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String imgname = "img_file_name.png";
qrCodeImage = ImageIO.read(new File("C:/Users/pathToTheFile/" + imgname));
try {
LuminanceSource source = new BufferedImageLuminanceSource(qrCodeImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
System.out.println("Decoded text===>" + new MultiFormatReader().decode(bitmap).getText());
} catch (NotFoundException e) {
System.out.println("barcode was not decoded successfully");
}
}
}

How to extract frames from a video java?

I'm working on a project to do analysis on a video, and I want to split the video into frames to process individually. I took a look at several open source libraries, including Xuggler and FFMPEG, but they are both outdated and unavailable for use. Is there a simple way that I can extract the frames from the video and process them as a collection of BufferedImage?
Follow this code
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber.Exception;
public class Read{
public static void main(String []args) throws IOException, Exception
{
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("D:/video.mp4");
frameGrabber.start();
IplImage i;
try {
i = frameGrabber.grab();
BufferedImage bi = i.getBufferedImage();
ImageIO.write(bi,"png", new File("D:/Img.png"));
frameGrabber.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Next I leave the code that #Rohit proposed, but updated to 2021
package com.example;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
public class Main {
public static void main(String []args) throws IOException, Exception
{
File myObj = new File("D:\\x\\x\\x\\x\\video.mp4");
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(myObj.getAbsoluteFile());
frameGrabber.start();
Frame f;
try {
Java2DFrameConverter c = new Java2DFrameConverter();
f = frameGrabber.grab();
BufferedImage bi = c.convert(f);
ImageIO.write(bi,"png", new File("D:\\x\\x\\x\\x\\img.png"));
frameGrabber.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You can use OpenCV Image and Video processing free open source framework. And also has a good Java wrapper.

Tess4j jar file issue

import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.Tesseract;
public class Tess4JSample {
public static void main(String[] args) throws Exception{
URL imageURL = new URL("http://s4.postimg.org/e75hcme9p/IMG_20130507_190237.jpg");
RenderedImage img = ImageIO.read(imageURL);
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
try {
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
String result = instance.doOCR(outputfile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
for this program I have put the jar files tess4j-1.5.0 and jai_imageio-1.1. But still it shows error
The import net.sourceforge cannot be resolved
Can anyone tell me what is the necessary action needs to be taken care for error resolution? I taken this program from stack overflow itself. Thanks! in advance.

Categories

Resources