Convert Image format in android java - java

How do i convert Image format from within my android application activity.
I have the code to convert image format using Java, but it doesn't output the image with good quality and also similar code is not working in Android's Java.

You didn't post any of your code, so i have no idea what is wrong with your code. but you can convert a image to PNG or JPEG like this:
try {
FileOutputStream out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); //100-best quality
out.close();
} catch (Exception e) {
e.printStackTrace();
}

For example, from Bitmap to JPG:
Bitmap bmp;
JPEG_QUALITY = 80;
bmp.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out);

Related

Convert Tif to JPEG cause wrong image colors

I´m using JAI to convert a tiff file into ajpeg file, but when the file is converted the colors are totally wrong. What´s wrong with my code? Is this a JAI Bug? When converting to PNG the file colors are working fine.
try {
FileSeekableStream stream = null;
stream = new FileSeekableStream(tiff);
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", stream, null);
RenderedImage image = dec.decodeAsRenderedImage(0);
JAI.create("filestore", image, output, "JPEG");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The output file:
The original file

Convert Tif image to byte[]

I tried to convert Tiff image to Byte[] but getting exception from java 1.8 sdk. I searched in google but did not get solution yet. Same code works for java 1.6.
public static byte[] convertImage(String dirName, String imageName)
{
try
{
//String dirName="C:\\Temp\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,imageName));
ImageIO.write(img, "tif", baos);
baos.flush();
byte[] bytearray = baos.toByteArray();
baos.close();
return bytearray;
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
variable img is always null in java 1.8 but 1.6 returns info.
Exception raised from sdk 1.8 as follows
java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(Unknown Source)
at javax.imageio.ImageIO.getWriter(Unknown Source)
at javax.imageio.ImageIO.write(Unknown Source)
at test.practice.net.ConverterImageUsing18.convertImage(ConverterImageUsing18.java:88)
at test.practice.net.ConverterImageUsing18.GetBase64BinaryAsString(ConverterImageUsing18.java:52)
at test.practice.net.ConverterImageUsing18.main(ConverterImageUsing18.java:42)
Any hits or sample code is appreciable.
ImageIO needs an additional plugin to read or write TIFF. The built-in formats are BMP, GIF, JPEG, PNG and WBMP. To read or write TIFF, you can use JAI (jai_imageio.jar), TwelveMonkeys ImageIO or similar.
Without a suitable plugin, ImageIO.read(...) simply returns null. This is the most likely reason why your img is null (and you get an exception). You might have JAI or similar installed in your Java 1.6 JRE, or you may be testing with a different file.
However, if you just want to get the bytes of the original file, there's no need to use ImageIO at all. Simply read the bytes from the file into a byte array, for example like this:
File file = new File(dirName, imageName);
int length = (int) file.length();
byte[] bytes = new byte[length];
try (DataInputStream input = new DataInputStream(new FileInputStream(file))) {
input.readFully(bytes);
}
Or in Java 8, you can write it more elegant (thanks, #JoopEggen):
File file = new File(dirName, imageName);
byte[] bytes = Files.readAllBytes(file.toPath());

how to decode a qrcode using zxing through webcam

i have a code to decode a qrcode that take a image file and decode it. am using zxing library. but how can i make this capture qrcode from webcam and decode it. what are the changes i need to do?? can any one plz explain this step by step.
here is the code:
public class QrCodeDecoder
{
public String decode(File imageFile)
{
BufferedImage image;
try
{
image = ImageIO.read(imageFile);
}
catch (IOException e1)
{
return "io outch";
}
// creating luminance source
LuminanceSource lumSource = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
// barcode decoding
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
}
catch (ReaderException e)
{
return "reader error";
}
return result.getText();
}
}
You are pretty far away from a solution, I don't think anyone can explain it "step by step". You will first need to find a library that is capable of grabbing an image from a webcam. You might start with this library, though I'm sure there are others.
Once you can capture an image, start to figure out if it is in a format that the above code expects. If you are lucky, it will be, if not you will have to convert between the two formats.

creating .bmp image file from Bitmap class

I've created an application that uses sockets in which the client receives the image and stores the data of the image in Bitmap class....
Can anyone please tell me how to create a file named myimage.png or myimage.bmp from this Bitmap object
String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decode(base64Code);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
Try following code to save image as PNG format
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
Here, 100 is quality to save in Compression. You can pass anything between 0 to 100. Lower the digit, poor quality with decreased size.
Note
You need to take permission in Android Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit
To save your image to .BMP format, Android Bitmap Util will help you. It has very simple implementation.
String sdcardBmpPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sample_text.bmp";
Bitmap testBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_text);
AndroidBmpUtil bmpUtil = new AndroidBmpUtil();
boolean isSaveResult = bmpUtil.save(testBitmap, sdcardBmpPath);
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}

streaming a jpeg using com.sun.image.codec.jpeg.JPEGImageEncoder vs javax.imageio.ImageIO

I have a BufferedImage object of a jpeg which needs to be streamed as servlet response.
The existing code streams the jpeg using JPEGImageEncoder which looks like this :
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(resp.getOutputStream());
resp.reset();
resp.setContentType("image/jpg");
resp.setHeader("Content-disposition", "inline;filename=xyz.jpg");
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
param.setQuality(jpegQuality, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(image);
I have noticed that this is resulting in the file size of the streamed jpeg to be tripled , unable to figure why.So I have tried using ImageIO to stream the jpeg
ImageIO.write(image, "jpg", out);
This works just fine, I am unable to decide why my predecessor has gone with the choice of JPEGImageEncoder and was wondering what issues would arise if I change to using ImageIO, I have compared both jpegs and couldn't really spot differences. Any thoughts?
To be clear, you've already a concrete JPEG image somewhere on disk or in database and you just need to send it unmodified to the client? There's then indeed absolutely no reason to use JPEGImageEncoder (and ImageIO).
Just stream it unmodified to the response body.
E.g.
File file = new File("/path/to/image.jpg");
response.setContentType("image/jpeg");
response.setHeader("Content-Length", String.valueOf(file.length()));
InputStream input = new FileInputStream(file);
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[8192];
try {
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
finally {
try { input.close(); } catch (IOException ignore) {}
try { output.close(); } catch (IOException ignore) {}
}
You see the mistake of unnecessarily using JPEGImageEncoder (and ImageIO) to stream image files often back in code of starters who are ignorant about the nature of bits and bytes. Those tools are only useful if you want to convert between JPEG and a different image format, or want to manipulate (crop, skew, rotate, resize, etc) it.

Categories