Image resizing in java - 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!

Related

picture rotated 90 degrees when copy the picture from URI to file

I was trying to copy a picture from URI to a file path. Then I read the picture from the path, but the picture I got was rotated 90 degrees down. Below is my function. Anybody can help on this?
public boolean copyPicture(Context context, Uri source, String dest) {
boolean result = false;
int bytesum = 0;
int byteread = 0;
File destFile = new File(dest);
String scheme = source.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme)
|| ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream inStream = null;
try {
inStream = context.getContentResolver().openInputStream(source);
if (!destFile.exists()) {
result = destFile.createNewFile();
}
if (result) {
FileOutputStream fs = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.flush();
fs.close();
}
} catch (Exception e) {
e.printStackTrace();
result = false;
}
}
return result;
}
EXIF INTERFACE is the answer. It allows you to read specified attributes from a image file.
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
try {
ExifInterface exif = new ExifInterface(path);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap correctBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
bitmap=correctBmp;
}
catch(Exception e){
}

Why i cannot show my byte[] image after converting it from bitmap?

I'm trying to write a method that accepts an image(Bitmap) and returns a byte[] array. finally, I try to write this byte[] array to a folder so I can see the difference, but my byte[] arraycan not displayed, and in addition, it is not scaled down! This is my method:
private byte[] changeSize(Bitmap image) {
byte[] picture;
int width = image.getWidth();
int height = image.getHeight();
int newHeight = 0, newWidth = 0;
if (width > 250 || height > 250) {
if (width > height) { //landscape-mode
newHeight = 200;
newWidth = (newHeight * width) / height;
} else { //portrait-mode
newWidth = 200;
newHeight = (newWidth * height) / width;
}
} else {
Toast.makeText(this, "Something wrong!", Toast.LENGTH_LONG).show();
}
Bitmap sizeChanged = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
//Convert bitmap to a byte array
int bytes = sizeChanged.getByteCount();
ByteBuffer bb = ByteBuffer.allocate(bytes);
sizeChanged.copyPixelsFromBuffer(bb);
picture = bb.array();
//Write to a hd
picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String fileName = edFile.getText().toString() + "_downscaled" + ".jpg";
File file = new File(picturePath, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(picture);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
I tried several hours to get my byte[] array visible, but I could simply not do this. Any help or hints to show me where I derail is/are very appreciated.
This was working for me
public static Bitmap byteArraytoBitmap(byte[] bytes) {
return (BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
public static byte[] bitmaptoByteArray(Bitmap bmp) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); //PNG format is lossless and will ignore the quality setting!
byte[] byteArray = stream.toByteArray();
return byteArray;
}
public static Bitmap bitmapFromFile(File file) {
//returns null if could not decode
return BitmapFactory.decodeFile(file.getPath());
}
public static boolean saveImage(Bitmap image, String filePath) {
LogInfo(TAG, "Saving image to: " + filePath);
File file = new File(filePath);
File fileDirectory = new File(file.getParent());
LogInfo(TAG, fileDirectory.getPath());
if (!fileDirectory.exists()) {
if (!fileDirectory.mkdirs()) {
Log.e(TAG, "ERROR CREATING DIRECTORIES");
return false;
}
}
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bitmaptoByteArray(image));
fo.flush();
fo.close();
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}

Uploading Image to Server to be downloaded by iOS

I am attempting to upload an image to my server in java and then download it in iOS within an app. When I upload / download with java, it works, but when I download it in iOS the image just turns up black. Also, when I view the image in browser it has a purple hue over it convincing me that the image is corrupt. Am I not uploading the image correctly?
Code:
public void uploadToServer() {
String server = "ip";
int port = 21;
String user = "name";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int w = 765;
int h = 503;
double d = .85;
BufferedImage img = resize(client.methods.getClientImage(),
(int) (w * d), (int) (h * d));
ImageIO.write(img, "JPG", os);
InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
String secondRemoteFile = "directory";
// System.out.println("Start uploading file");
OutputStream outputStream = ftpClient
.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
ftpClient.completePendingCommand();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Heres the purple tint:
iOS Code:
- (void) refreshImage {
client.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:#"http://link.jpg"]]]; ;
}

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!

Converting BMP Type

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.

Categories