I am trying to reduce image size mb to kb using bitmap. but the code I have done is not working. I am new in android programming please can anyone help.
thanks.
I expect like this to convert image.
enter image description here
I have tried this
public void compressBitmap(File file, int sampleSize, int quality) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
FileInputStream inputStream = new FileInputStream(file);
Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
File files = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
FileOutputStream outputStream = new FileOutputStream(files);
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.close();
long lengthInKb = file.length() / 1024; //in kb
if (lengthInKb > 1000) {
compressBitmap(file, (sampleSize*2), (quality/4));
}
selectedBitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I want to compress jpg file if it bigger than 1MB to 1MB or a bit smaller.
Param compressionQuality from 0.0f to 1.0f in setCompressionQuality in ImageWriteParam is not clearly defined.
Quality = 0.5f can compress the image 5 times, 7 times, 1.2 times depends on the image. Not 2 times as everybody expected.
So, how can I choose the size of compressing image? Maybe there are any open source libraries?
UPD:
Example of compressing:
public static byte[] write(BufferedImage image, String formatName, int dpi, float quality) {
try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
ImageIOUtil.writeImage(image, formatName, outputStream, dpi, quality);
return outputStream.toByteArray();
} catch (IOException ex) {
return null;
}
}
public static void main(String[] args) {
BufferedImage bufImg = null;
try
{
bufImg = ImageIO.read(new File("myfile"));
} catch (IOException e){e.printStackTrace();}
for(int i = 0; i < 10; i++) {
byte[] arr = write(bufImg, "jpg", 300, 0.1f*i);
double fl = (double)arr.length/(double)MY_FILE_SIZE_BYTES;
System.out.println(fl + " " + (0.1f*i));
}
}
I use org.apache.pdfbox.tools.imageio.ImageIOUtil for that, ImageIOUtil uses ImageWriter and ImageWriteParam inside.
I'm encountering an issue with bitmap factory.
I've got a method to reduce and rotate an image to show a preview in an image view, but I would like to save this with the new size.
I'm just turning around with inputfilestream and outputfilestream but don't get to save it.
Is anybody know a clear method to put my bitmap in an outpufilestream?
Thanks a lot
here's my code
#Override
protected void onResume() {
super.onResume();
File[] fileArray;
final File root;
File chemin = Environment.getExternalStorageDirectory();
String filepath = chemin + "/SmartCollecte/PARC/OUT/" + fichano + "_" + conteneur_s+"_"+cpt+".jpg";
try {
decodeFile(filepath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap b1 = BitmapFactory.decodeFile(filePath, o2);
Bitmap b = ExifUtils.rotateBitmap(filePath, b1);
FileOutputStream fos = new FileOutputStream(filePath);
b.compress(Bitmap.CompressFormat.PNG,100,fos);
fos.close();
showImg.setImageBitmap(b);
}
Have you tried doing it like this?
Assuming bitmap is bitmap you want to save.
Also, take a look at some existing system directories.
final FileOutputStream fos = new FileOutputStream(new File(filepath + "_scaled.jpg"));
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
} catch (IOException e) {
// handle exception
} finally {
fos.close
}
Source
Where first parameter of Bitmap.compress() is your desired output format (see CompressFormat) and the second parameter is compression quality.
ok I found out what was missing.
had to create a new byte array to convert my bitmap to file :
String filepathcomp = Environment.getExternalStorageDirectory()+"/SmartCollecte/PARC/OUT/"+ fichano + "_" + conteneur_s+"_"+cpt+".jpg";
File f = new File(filepathcomp);
Bitmap newbitmap = b;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newbitmap.compress(Bitmap.CompressFormat.JPEG,80,bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
I'm capturing an Image with the Camera. I save the File in the public photo directory and save the Uri to that file.
I want to save the Image in a Base64 String and put it on a HashMap to put it then in a XML file later.
protected Void doInBackground(Void...voids) {
options.inJustDecodeBounds = false;
//Bitmap bmp = BitmapFactory.decodeFile(imageFilePath,options);
InputStream in = null;
try {
in = getContentResolver().openInputStream(Uri.parse(mCurrentPhotoPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeStream(in,null,options);
int imgHeight = image.getHeight();
int imgWidth = image.getWidth();
while(imgHeight>2000){
imgHeight = imgHeight / 2;
}
while(imgWidth>2000){
imgWidth = imgWidth / 2;
}
Bitmap test = Bitmap.createScaledBitmap(image,imgWidth,imgHeight,false);
String stest = base64EncodeDecode.encodeToBase64(test);
items.put("image",base64EncodeDecode.encodeToBase64(test);
return null;
}
The Base64 takes too long to encode it.
encodeToBase64 Method
public String encodeToBase64(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
Can you tell me if I do something wrong while encoding?
I hope my problem is clear.
Kind Regards!
If you are getting !!! FAILED BINDER TRANSACTION !!! error is probably because you are passing to much data to the other Activity, there is a limit of how much you can send. Try compressing your image to 50% or 30% image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
I am uploading file using the above code, the code works fine .
My question is, is it possible to restrict image to 75 kb only during image upload ??
In case it exceeds 75 kb, I dont want to throw an exception, but continue upload with what I got
private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public final static int MAX_SIZE = 75000;
private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
int size = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while (size < MAX_SIZE && (read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
size += read;
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
There are various way to do it . if you are Using Struts then Edit Strtus.xmland Use where value Denotes File Size limit
<constant name="struts.multipart.maxSize" value="30000000" />
Servlet
#MultipartConfig(
location="/tmp",
fileSizeThreshold=1024*1024, // 1 MB
maxFileSize=1024*1024*5, // 5 MB
maxRequestSize=1024*1024*5*5 // 25 MB
)
or
<max-file-size>20848820</max-file-size>
Java
final static int MAX_SIZE = 50000;//Max Limit of File
You can use below code to calculate file size in kb.
long fileSize = file.length()/1024;
System.out.println("fileSize="+fileSize);
if(fileSize==75){
}else{
}
I am tring to create an image file from database on disk. I wrote the following code:
{
oracle.sql.BLOB blob1 = (BLOB) rs.getBlob(1);
//fillFilePath is file path
File blobFile = new File(fillFilePath);
String checkExe[]=fillFilePath.split("\\.");
FileOutputStream outStream = new FileOutputStream(blobFile);
InputStream inStream = blob1.getBinaryStream();
int length = -1;
int size = blob1.getBufferSize();
byte[] buffer = new byte[size];
BufferedImage image = ImageIO.read( inStream );
System.out.println("Inside image upload");
System.out.println("Inside image jpg");
ImageIO.write(image, "JPG", outStream);
But it is not working.
Please give me any suggestions?
try:
BLOB image = ((OracleResultSet) rs).getBLOB("image");
blobLength = image.length();
chunkSize = image.getChunkSize();
binaryBuffer = new byte[chunkSize];
for (position = 1; position <= blobLength; position += chunkSize)
{
bytesRead = image.getBytes(position, chunkSize, binaryBuffer);
outputFileOutputStream.write(binaryBuffer, 0, bytesRead);
totbytesRead += bytesRead;
totbytesWritten += bytesRead;
}
BufferedImage bi= ImageIO.read(obj.getPhoto().getBinaryStream());//photo is Blob.
File outputfile = new File("folderInYourProject\\"+nameVar+".jpg");
ImageIO.write(bi, "jpg", outputfile);