Problem with colors after converting image - java

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;
}
}
}

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 :(

How to Get Total Page Count From Tiff

I have started to create a new method in our project to return total pages. We are using TIFFTweaker which can be referenced from the following URL - https://github.com/dragon66/icafe/blob/master/src/com/icafe4j/image/tiff/TIFFTweaker.java
In this class I found a method TIFFTweaker.getPageCount() which looks like it wants a RandomAccessInputStream object for their getPageCount().
I've been playing around with trying to get from my file object over to what they're looking for.
What would be the best way to approach this and return the total pages from the tiff?
I have looked over some java docs, stackOverflow and some random blogs but can't seem to figure out how to get from a file object to a randomaccessinputstream.
#Override
public Integer totalPages(File file) {
Integer numberOfPages = 0;
try{
//TIFFTweaker.getPageCount(); - How to pass the file and get the count? Problem is type is a random access input stream and I have a file type
FileInputStream fileInputStream = new FileInputStream(file);
String absolutePath = file.getAbsolutePath();
// return TIFFTweaker.getPageCount();
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
I am expecting a numeric value returned which represents the total number of pages in the TIFF file I'm passing.
Here is what I got to work. #roeygol, thanks for your answer. I had tried to Maven import the dependency but something was broken in that version. Here is what I came up with.
#Override
public Integer totalPages(File file) {
try(
InputStream fis = new FileInputStream(file);
RandomAccessInputStream randomAccessInputStream = new
FileCacheRandomAccessInputStream(fis)
){
return TIFFTweaker.getPageCount(randomAccessInputStream);
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
Try to use this code:
import java.io.File;
import java.io.IOException;
import java.awt.Frame;
import java.awt.image.RenderedImage;
import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class MultiPageRead extends Frame {
ScrollingImagePanel panel;
public MultiPageRead(String filename) throws IOException {
setTitle("Multi page TIFF Reader");
File file = new File(filename);
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
System.out.println("Number of images in this TIFF: " +
dec.getNumPages()); //<< use this function to get the number of pages of your TIFF
// Which of the multiple images in the TIFF file do we want to load
// 0 refers to the first, 1 to the second and so on.
int imageToLoad = 0;
RenderedImage op =
new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
null,
OpImage.OP_IO_BOUND,
null);
// Display the original in a 800x800 scrolling window
panel = new ScrollingImagePanel(op, 800, 800);
add(panel);
}
public static void main(String [] args) {
String filename = args[0];
try {
MultiPageRead window = new MultiPageRead(filename);
window.pack();
window.show();
} catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
Prerequisites for this code is to use jai-codec:
https://mvnrepository.com/artifact/com.sun.media/jai-codec/1.1.3
The main function to be used for is getNumPages()

how to convert JPEG image to TIFF image?

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");

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.

Issue in saving image to desktop

Trying to save a image from this URL which gets transformed to a image. Looks like I am missing something, the image is not getting saved on the desktop
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class Image {
public static void main(String[] args) {
BufferedImage image = null;
try {
String url = "http://ramp.sdr.co.za/zp-core/i.php?a=1402NYFW/NicholasK&i=1402_NYFW_1005_NicholasK.JPG&w=387&h=580&cw=&ch=&q=92&wmk=!";
String imgPath = null;
imgPath = "C:/temp" + "a" + "";
URL imageUrl = new URL(url);
image = ImageIO.read(imageUrl);
if (image != null) {
System.out.println("in here");
File file = new File(imgPath);
ImageIO.write(image, "jpg", file);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You may not have appropriate user privileges to write to "C:/tempa". Event if you decided to use "c:/temp", the folder may not exist and you may not have the required privileges to either create it or write to it.
You could use System.getProperties("user.home"), which will return the current users home directory, which is more likely to allow you to write to it
String imgPath = System.getProperties("user.home") + "/a image.jpg";
File file = new File(imgPath);
ImageIO.write(image, "jpg", file);
I'd also add a else statement to your if statement so you can see when the image didn't load

Categories

Resources