I am writing some text on Image which will be compressed.
Image sie 2048 x 1536
Something px
I first tried to write first It throws OutOfMemory Exception
then i first compressed it to 1024 x 768
Then Written text on the Image
It increased the Image KB's from 100KB
to 640KB
While writing text i can compromise
the Image quality but not the text Quality
on Compression quality set to 30
the text also goes downsample
Questions:
is there any process to
write then compress
orCompress then Write
text without changing the ImageSize(in KB)?I want Image Size(in KB) as less as Possible?
And also When inSampleSize is set to 3 it does not work and only the image of 2048 , 1024 , 512 using 1 , 2 , 4 is created as output I want image of some size arround 700px maintaining aspect ration.
Codes:.
Method for StampingImage
public void stampMyImage(String filePath, String text, Bitmap bitmap) {
String[] str = text.split("\n");
filePath = "/sdcard/geoTag/1imagelong_001_001_0002_0002_1135_130708144229.jpg";
bitmap = BitmapFactory.decodeFile(filePath);
if (bitmap != null) {
Bitmap dest = null;
try {
dest = bitmap.copy(bitmap.getConfig(), true);
} catch (OutOfMemoryError e1) {
Log.e("Exception", e1.getMessage());
e1.printStackTrace();
} catch (Error e) {
Log.e("Exception", e.getMessage());
e.printStackTrace();
}
Canvas cs = new Canvas(dest);
Typeface tf = Typeface.create("Verdana", Typeface.BOLD);
Paint tPaint = new Paint();
tPaint.setAntiAlias(true);
tPaint.setTextSize(40);
tPaint.setTextAlign(Align.LEFT);
tPaint.setTypeface(tf);
tPaint.setColor(Color.RED);
tPaint.setStyle(Style.FILL_AND_STROKE);
cs.drawBitmap(bitmap, 0f, 0f, null);
float textHeight = tPaint.measureText("yY");
int index = 0;
for (String Oneline : str) {
cs.drawText(Oneline, 20f, (index + 1) * textHeight + 25f,
tPaint);
index++;
}
try {
FileOutputStream fos = new FileOutputStream(
"/sdcard/timeStampedImage.jpg");
dest.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Method for Regular Compression
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
int quality = 70;
myBitmapClose = BitmapFactory.decodeFile(imgUriClose.getPath(),options);
if (myBitmapClose != null) {
File sdImageMainDirectory = new File(imgUriClose.getPath());
try {
FileOutputStream fileOutputStream = new FileOutputStream(sdImageMainDirectory);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
myBitmapClose.compress(CompressFormat.JPEG, quality, bos);
if (bos != null) {
bos.flush();
bos.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image Sample
See Also
Some useful links i followed
How to write text on an image in Java (Android)
Generate a image with custom text in Android
Drawing Text (TimeStamp) Over image captured from Standalone Camera