Converting BMP Type - java

I tried to convert a bmp:
File file = new File(source.getText());
try {
BufferedImage i = ImageIO.read(file);
if (i != null) {
BufferedImage convertedImg = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
boolean drawImage = convertedImg.getGraphics().drawImage(i, 0, 0, null);
File f = new File(output.getText().concat(File.separatorChar + "out.bmp"));
boolean write = ImageIO.write(convertedImg, "BMP", f);
} else {
//...
}
}catch (Exception e) {
e.printStackTrace();
}
But it doesn't write the image correctly. As I open the bmp it says the file is empty?? What am I doing wrong?
Edit: write returns false.

Related

Java android change black color in picture to tracspadence and save in file

Hi I want to rotate my image and save in file I did this :
for (int i = 0; i < 361; i++) {
Bitmap bm = RotateMyBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.znacznik_new), i);
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "ikona"+i+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
try {
fOut.flush(); // Not really required
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close(); // do not forget to close the stream
} catch (IOException e) {
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static Bitmap RotateMyBitmap(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
And I rotate image and I have files but a image have a black background and my oryginal image doesn't have a black background it have transpadence . How I can change a black color to transpadence and save in file
JPEG doesn't support transparency, all the transparent parts will turn black.
Compress the bitmap with Bitmap.CompressFormat.PNG.
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);

How to convert BufferedImage RGBA to BufferedImage RGB?

So I tried looking for the solution but could not find a solution where I can convert the RGBA to RGB format.
If a simple solution from BufferedImage to BufferedImage conversion is given then that will be best, otherwise the problem is as follows :
Basically I have to convert BufferedImage into MAT format. It works properly for JPG/JPEG images but not PNGs. Following code I use for the conversion ::
BufferedImage biImg = ImageIO.read(new File(imgSource));
mat = new Mat(biImg.getHeight(), biImg.getWidth(),CvType.CV_8UC3);
Imgproc.cvtColor(mat,matBGR, Imgproc.COLOR_RGBA2BGR);
byte[] data = ((DataBufferByte) biImg.getRaster().getDataBuffer()).getData();
matBGR.put(0, 0, data);
This throws error for images with RGBA values. So thus looking for a solution.
Thanks in advance.
I found a solution like this :
BufferedImage oldRGBA= null;
try {
oldRGBA= ImageIO.read(new URL("http://yusufcakmak.com/wp-content/uploads/2015/01/java_ee.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final int width = 1200;
final int height = 800;
BufferedImage newRGB = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
newRGB .createGraphics().drawImage(oldRGBA, 0, 0, width, height, null);
try {
ImageIO.write(newRGB , "PNG", new File("your path"));
} catch (IOException e) {}
So here when we creating new BufferedImage we can change type of the image with :
The RGB worked for me with PNG.
public static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
if (original.getType() == type) {
return original;
}
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
}
finally {
g.dispose();
}
return image;
}

Creation of GIF is taking so long time in Android

I am creating a app which burst capture images and create a GIF as output. My problem is creation of GIF from the image sequence is taking so long time, whether the resolution of images are 320x240. I am using AnimatedGifEncoder class for GIF encoding. as follow this link.
My code for creation of GIF is as following
private void saveGifImage() {
FileOutputStream outStream =
String fileName = "test.gif";
try {
File file = new File(Environment.getExternalStorageDirectory() + "/gif_convertor/sample/");
if (!file.exists())
file.mkdirs();
File file1 = new File(file + File.separator +
if (file1.exists()) {
} else {
try {
// file1.mkdirs();
file1.createNewFile();
} catch (Exception e) {
}
}
outStream = new FileOutputStream(file1);
Log.d("Location", file1.getPath().toString());
outStream.write(generateGIF());
outStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DialogUtils.stopProgressDisplay();
}
}
private byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
encoder.delay = 33; // 50 means 0.5 seconds ( 100 value is equivalent to 1 seconds)
encoder.repeat = 0; // 0 means repeat forever, other n positive integer means n times repeat , -1 means no repeat
encoder.sizeSet = true; // resize allowed with true flag
encoder.width = 320;
encoder.height = 240;
File tempDir = new File(getActivity().getExternalFilesDir(null), "temp");
if (tempDir.exists()) {
for (File file : tempDir.listFiles()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
encoder.addFrame(bitmap);
}
}
encoder.finish();
return bos.toByteArray();
}

How to create an image from an InputStream, resize it and save it?

I have this code where i get an InputStream and create an image:
Part file;
// more code
try {
InputStream is = file.getInputStream();
File f = new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg");
OutputStream os = new FileOutputStream(f);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
} catch (IOException e) {
System.out.println("Error");
}
The problem is that I have to resize that image before i create if from the InputStream
So how to resize what I get from the InputStream and then create that resized image. I want to set the largest side of the image to 180px and resize the other side with that proportion.
Example:
Image = 289px * 206px
Resized image = 180px* 128px
I did this:
try {
InputStream is = file.getInputStream();
Image image = ImageIO.read(is);
BufferedImage bi = this.createResizedCopy(image, 180, 180, true);
ImageIO.write(bi, "jpg", new File("C:\\ImagenesAlmacen\\QR\\olaKeAse.jpg"));
} catch (IOException e) {
System.out.println("Error");
}
BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
And I did not use the other code.
Hope helps someone!

Image resizing in java

I have used the below code for resizing a image and storing it in a temp file
public File resizeImage(InputStream fileInputStream, String fileName, int newW,int newH) throws Exception {
Graphics2D g = null;
File file2= File.createTempFile("result",FilenameUtils.getExtension(fileName));
BufferedImage img = null;
File tempFile1 = File.createTempFile("Temp1File",FilenameUtils.getExtension(fileName)); // If not resizing send temp file1
FileOutputStream outputStream = null;
try{
outputStream = new FileOutputStream(tempFile1);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
outputStream = null;
img = ImageIO.read(new FileInputStream(tempFile1));
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
ImageIO.write(dimg, FilenameUtils.getExtension(fileName), file2);
} catch(SocketException e) {
e.printStackTrace();
throw e;
} catch(Exception e) {
e.printStackTrace();
throw e;
} finally {
if(outputStream != null)
outputStream.close();
if(fileInputStream != null)
fileInputStream.close();
if(g != null)
g.dispose();
if(img != null)
img.flush();
}
return file2;
}
When I am reading tempFile1 in the highlighted line I am getting exception
Socket Exception : Socket already closed.
Can anyone help me with this
you can use imgscalr for this purpose!

Categories