I want to capture edit text content in image. But text can be scrollable.
How to capture with scrollable content from edit text?
without scrollable i am using the following link to do..
Create Bitmap Image from EditText & its content
Please help me to solve the issue
Here is the sample code
please try your best...
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.edittextimage);// get the image same as your EditText
bitmap = convertToMutable(bitmap);// converting the bitmap to mutable
Canvas cs = new Canvas(bitmap);
int h = bitmap.getHeight();
int w = bitmap.getWidth();
Paint pt = new Paint();
pt.setColor(Color.GREEN);
String iam = "your text that get from the Edit Text";
cs.drawText(iam, 0, iam.length(), (h / 2) + 10, (w / 2) / 2, pt);
pt.setColor(Color.RED);
cs.drawText("this is praki", 0, 13, h / 2, w / 3, pt);
Save_to_SD(bitmap , path)//save the bitmap in to sdcard
convertToMutable(bitmap) Methode ....
public static Bitmap convertToMutable(Bitmap imgIn) {
try {
// this is the file going to use temporally to save the bytes.
// This file will not be a image, it will store the raw image data.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temp.tmp");
// Open an RandomAccessFile
// Make sure you have added uses-permission
// android:name="android.permission.WRITE_EXTERNAL_STORAGE"
// into AndroidManifest.xml file
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
// get the width and height of the source bitmap.
int width = imgIn.getWidth();
int height = imgIn.getHeight();
Bitmap.Config type = imgIn.getConfig();
// Copy the byte to the file
// Assume source bitmap loaded using options.inPreferredConfig =
// Config.ARGB_8888;
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE,
0, imgIn.getRowBytes() * height);
imgIn.copyPixelsToBuffer(map);
// recycle the source bitmap, this will be no longer used.
imgIn.recycle();
System.gc();// try to force the bytes from the imgIn to be released
// Create a new bitmap to load the bitmap again. Probably the memory
// will be available.
imgIn = Bitmap.createBitmap(width, height, type);
map.position(0);
// load it back from temporary
imgIn.copyPixelsFromBuffer(map);
// close the temporary file and channel , then delete that also
channel.close();
randomAccessFile.close();
// delete the temp file
file.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgIn;
}
Save_to_SD(bitmap , path) methode....
public static void Save_to_SD(Bitmap bm, String image_name) {
// String extStorageDirectory =
// Environment.getExternalStorageDirectory()
// .toString();
// String meteoDirectory_path = extStorageDirectory +
// "/Weather_Belgium";
OutputStream outStream = null;
File file = new File(image_name);
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Log.i("Hub", "OK, Image Saved to SD");
Log.i("Hub",
"height = " + bm.getHeight() + ", width = " + bm.getWidth());
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: " + e.toString());
}
}
Related
I am taking screenshot programmatically using the following code:
public static Bitmap takeScreenshot(View view)
{
try
{
// create bitmap screen capture
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
catch (Throwable e)
{
CustomLogHandler.printError(e);
}
return null;
}
private static void copyFile(Bitmap bitmap)
{
File dstFile = getShareResultFile();
//Delete old file if exist.
if(dstFile.exists()) {
dstFile.delete();
}
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(dstFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
fos.flush();
}
catch (Exception e) {
CustomLogHandler.printError(e);
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
CustomLogHandler.printError(ioe);
}
}
}
}
There are several problem like:
Back arrow, title and share menu background color is not correct. It looks messy.
Background color of toolbar is totally changed.
Image quality is too poor and list items rounded drawable has not smooth corners.
Background of layout is not taken that I set as background of my parent layout.
I am taking the screenshot from the root view.
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
First, you are saving this as a JPEG. JPEG is designed for photos, and your screenshot is not a photo.
Second, you are saving this with a quality factor of 0. JPEG uses a lossy compression algorithm, and a quality factor of 0 says "please feel free to make this image be really poor, but compress it as far as you can".
I suggest switching to:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
PNG is a better image format for a screenshot with the contents shown in your question. I don't think PNG uses the quality factor value; I put in 100 just to indicate that you want the best possible quality.
public static Bitmap takeScreenshot(View view)
{
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
This code can save view as bitmap.
But after you update your question with save code I see that you set 0 for quality, and what you expect?
#param quality Hint to the compressor, 0-100. 0 meaning compress for
* small size, 100 meaning compress for max quality. Some
* formats, like PNG which is lossless, will ignore the
* quality setting
just use your Ctrl button + click on method name to read doc about params
the answer is set second parameter 100 instead of 0!
Try using this:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
and
public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}
Images are saved in the external storage folder.
try this
private void captureScreen() {
View v = this.getWindow().getDecorView().findViewById(android.R.id.content);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File file = new File(extr, getString(R.string.free_tiket) + ".jpg");
FileOutputStream f = null;
try {
f = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
f.flush();
f.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
This question already has answers here:
Android saving file to external storage
(13 answers)
Closed 2 years ago.
I develop app that save images to sd Card and all the pictures are upside i want to rotate them and save them in the rotate position i choose .
i know how to rotate on my code but the image is not saved permanently.
here is my code :
//Rotate the picture
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}
//Resize image
public void resizeImage(String path , int Wdist,int Hdist){
try
{
int inWidth = 0;
int inHeight = 0;
InputStream in = new FileInputStream(path);
// decode image size (decode metadata only, not the whole image)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;
// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;
// decode full image pre-resized
in = new FileInputStream(path);
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/Wdist, inHeight/Hdist);
// decode full image
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, Wdist, Hdist);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
// resize bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
// save image
try
{
FileOutputStream out = new FileOutputStream(path);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
Log.e("Image", e.getMessage(), e);
}
}
thanks for the helpers :)
You'll need to save the Bitmap back.
try {
File dir = new File("path/to/directory");
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "original_img_name.png");
FileOutputStream out;
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
out.close();
} catch(Throwable ignore) {}
}
Edit 1 :
Replace
bmp.compress(Bitmap.CompressFormat.PNG, 90, out); with
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); and set correct values for the directory path and the image name. If you want to replace the previous images, use the original path and image name.
Also, make sure you include the following permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can also try this one
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, true);
Go through this link
how to rotate a bitmap 90 degrees
The following code can help you compress and resize the bitmap.
Note:
Create a String type variable with name of photoPath and store the photo url in it.
public void compressImage(){
Log.i("compressPhoto", "Compress and resize photo started.");
// Getting Image
InputStream in = null;
try {
in = new FileInputStream(photoPath);
} catch (FileNotFoundException e) {
Log.e("TAG","originalFilePath is not valid", e);
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap = bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.2), (int)(bitmap.getHeight()*0.2), true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byteArray = stream.toByteArray();
// Storing Back
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(photoPath);
outStream.write(byteArray);
outStream.close();
} catch (Exception e) {
Log.e("TAG","could not save", e);
}
}
On a rooted Android device, i want to take a screenshot and convert the raw format image to a Png image then save it locally. So far, i managed to access the framebuffer, take the screenshot and save the raw image. The problem is when i convert it to Png format, the image i get is all wrong.. a bunch of white and grey lines.
Here's what i did:
public void putRawImageInArray (byte [] array, File f ) throws IOException{
#SuppressWarnings("resource")
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f)); //The framebuffer raw image is in the file
bufferedInputStream.read(array, 0, array.length);//read the file
}
public void convertToBitmap (byte [] rawarray) throws IOException{
byte [] Bits = new byte[rawarray.length*4];
int i;
for(i=0;i<rawarray.length;i++)
{
Bits[i*4] =
Bits[i*4+1] =
Bits[i*4+2] = (byte) ~rawarray[i];
Bits[i*4+3] = -1;//0xff, that's the alpha.
}
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
File f = new File(Environment.getExternalStorageDirectory(), "/pictures/picture.png");
f.createNewFile();
if (f.exists() == true) {
f.delete();
}
try{
OutputStream fos=new FileOutputStream(f);
bm.compress(CompressFormat.PNG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
What am i doing wrong?
Try removing all this
byte [] Bits = new byte[rawarray.length*4];
int i;
for(i=0;i<rawarray.length;i++)
{
Bits[i*4] =
Bits[i*4+1] =
Bits[i*4+2] = (byte) ~rawarray[i];
Bits[i*4+3] = -1;//0xff, that's the alpha.
}
and use rawarray directly
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(rawarray));
and make sure that the color model that you are using(Bitmap.Config.ARGB_8888) is same as the color model of the image data.
I have my SurfaceView up and running with a button to open the camera and take a picture which is used as the background and another button to add items that sit on top and can be moved around. This all works fine until I try to save the SurfaceView as a Bitmap when all I get is the background and none of the images on top.
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(_mGotImage){
canvas.drawBitmap(_mImage, 0, 0, null);
}else{
canvas.drawColor(Color.BLACK);
}
//if the array is not empty
if(!_mJazzItems.isEmpty()){
//step through each item in the array
for(JazzItem item: _mJazzItems){
//get the bitmap it is using
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.getBitmap());
//and draw that bitmap at its X and Y coords
canvas.drawBitmap(bitmap, item.getX(), item.getY(), null);
}
}
}
This is the method called to try and save the Canvas.
public void screenGrab(){
Bitmap image = Bitmap.createBitmap(_mPanelWidth, _mPanelHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
this.onDraw(canvas);
String path=Environment.getExternalStorageDirectory() + "/test2.png";
File file = new File(path);
try{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
}catch (Exception e){
e.printStackTrace();
}
}
The onDraw works fine, I get my camera shot in the background and can add all my items over the top and move them around. Just when I try to get a screen shot, none of the items on top are present.
Thanks for any help!!
-- UPDATE --
I have modified the screen grab method to this:
public void screenGrab(){
Bitmap image = Bitmap.createBitmap(_mPanelWidth, _mPanelHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawBitmap(_mImage, 0, 0, null);
//if the array is not empty
if(!_mJazzItems.isEmpty()){
//step through each item in the array
for(JazzItem item: _mJazzItems){
//get the bitmap it is using
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.getBitmap());
//and draw that bitmap at its X and Y coords
canvas.drawBitmap(bitmap, item.getX(), item.getY(), null);
}
}
String path=Environment.getExternalStorageDirectory() + "/test2.png";
File file = new File(path);
try{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
}catch (Exception e){
e.printStackTrace();
}
}
I can't see why this is not drawing the other images over the top...
in my case i am using this:
public static Bitmap combineImages(Bitmap c, Bitmap overLayImage, Context con) {
Bitmap cs = null;
int width, height = 0;
width = c.getWidth();
height = c.getHeight();
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0, 0, null);
String left = yourleftPosition;
String top = yourtopPosition;
comboImage.drawBitmap(overLayImage, Float.parseFloat(left), Float.parseFloat(top),null);
/******
*
* Write file to SDCard
*
* ****/
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
String pathis = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/" + tmpImg;
os = new FileOutputStream(pathis);
cs.compress(CompressFormat.PNG, 100, os);
}
catch (IOException e) {
Log.e("combineImages", "problem combining images", e);
}
return cs;
}
this question is easy,we can :
public static void writePhotoJpg(Bitmap data, String pathName) {
File file = new File(pathName);
try {
file.createNewFile();
// BufferedOutputStream os = new BufferedOutputStream(
// new FileOutputStream(file));
FileOutputStream os = new FileOutputStream(file);
data.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
but this method not all successful:because "Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels)." in the google document. without luck i have this problem: in the Camera preview i used :
private Bitmap printScreen() {
View view = this.getWindow().getDecorView();
// if (view.isDrawingCacheEnabled()) {
view.setDrawingCacheEnabled(true);
Calendar c = Calendar.getInstance();
String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND);
// }
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
return bmp ;
}
so when i used setImageBitmap(bmp) ,looks very well,but when i open the save jpeg file it is a black jpeg.so i think the save method is not well,can you tell me another save method?
you can try this:
public static final int BUFFER_SIZE = 1024 * 8;
static void writeExternalToCache(Bitmap bitmap, File file) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
bitmap.compress(CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
it works in my code, so if it's not work, try to find error:
1.the bitmap display right ?
2.where is the bitmap save file? the file has some limit? like size or ...
if the error is your post reason, you can try decode the bitmap again using Bitmap.Config.RGB_565.
Use .getRootView() method of view OR the layout contains this view, use it (e.g.) mainLayout contain one image view at index 1 then mainlayou.getChildAt(1) to get the view.
E.g.
View v1 = mainLayout.getChildAt(1); //OR View v1 = mainLayout.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
Hope helpful to you...