how to save image to file android custom view? - android

I have a question.
I try to save canvas image to file
here is how i work.
1.Create canvas object with bitmap(form image)
2.print Text on canvas (Using drawText)
3.save with bitmap.compress() method
but it saved only original bitmap(with out text)
I wonder how I can save text printed bitmap to file?
Here is my code
protected class MyView extends View{
public MyView(Context context){
super(context);
}
public void onDraw(Canvas canvas){
Paint pnt = new Paint();
pnt.setColor(Color.BLACK);
canvas.scale(0.5f,0.5f);
Resources res = getResources();
BitmapDrawable bd =(BitmapDrawable)res.getDrawable(R.drawable.hanhwa);
Bitmap bit = bd.getBitmap();
canvas.drawBitmap(bit,0,0,null);
pnt.setTextSize(30);
canvas.drawText("hello",290,340,pnt);
canvas.restore();
//file save//
File folder = new File(Environment.getExternalStorageDirectory()+"/DCIM/tmp");
boolean isExist = true;
if(!folder.exists()){
isExist = folder.mkdir();
}
if(isExist){
File file = null;
boolean isFileExist = false ;
file = new File(folder.getPath() + "/tmp.jpg");
if(file != null && !file.exists()){
try{
isFileExist = file.createNewFile();
} catch(IOException e){
e.printStackTrace();
}
}
else{
}
if(file.exists()){
FileOutputStream fos = null;
try{
fos = new FileOutputStream(file);
bit.compress(Bitmap.CompressFormat.JPEG,100,fos);
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
else{
//Toast.makeText(MyView.this,"foler not exist.",Toast.LENGTH_LONG).show();
}
}
}

Bitmap.compresss()
this method write a compressed version of the bitmap to the specified outputstream.
Pass bitmap instance to canvas
Here is the pseudo-code.
(except other statement, ex. try-catch, statement)
Canvas c = new Canvas(bit);
c.drawText("hello",290,340,pnt);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
this post will be helpful too.

Related

Capture a part of application and save it

In my app i want to capturea a part of my android application UI and save it programmatically .
For example i want do this actions :
In Activity/Fragment user clicks one Button .
capture from a part of Layout for example a LinearLayout that have id="captureMe" .
Save captured image somewhere .
how i can implement it ?
You can simply use this function just pass your view object
public Bitmap viewToBitmap(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Then Save this file
public void saveImage(Bitmap inImage) {
String root = Environment.getExternalStorageDirectory().toString();
File mydir = new File(root + "/demo/");
mydir.mkdirs();
String fname = "Image.jpeg";
File file = new File (mydir, fname);
String path2=file.getPath();
Uri uri=Uri.fromFile(file);
try {
FileOutputStream out = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
Try this, hope it works
LinearLayout captureMe = (LinearLayout)findViewById(R.id.captureMe);
captureMe.setDrawingCacheEnabled(true);
captureMe.buildDrawingCache();
bitmap = captureMe.getDrawingCache();
First Use this function to get bitmap of view that you want to capture:
public static Bitmap getViewBitmap(View v, int width, int height) {
Bitmap viewBitmap = Bitmap.createBitmap(width , height,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(viewBitmap);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return viewBitmap;
}
Then use this code to save this bitmap to storage:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
try {
fOutputStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}

How to convert xml layout to pdf in android

I tried a lot searching over the internet but I didn't find any solution regarding this. My problem is I have a layout called main.xml whose parent layout is a LinearLayout and it is scrollable. I want to generate a pdf of that layout. The layout consist of reports so I want to export those reports in pdf format. How can I do it Please help.
You can use this library to make it easy to do within a few lines of code -
PdfGenerator.getBuilder()
.setContext(context)
.fromLayoutXMLSource()
.fromLayoutXML(R.layout.layout_your_scroll_view)
.setDefaultPageSize(PdfGenerator.PageSize.A4)
.setFileName("Test-PDF")
.build();
You can also set inflated scroll view(s) instance (both single or multiple views) in it. Additionally you can also pass a callback (PdfGeneratorListener()) in .build() to notify about if the pdf generation is done or failed for an exception
At last I got the solution for my problem. Now I can easily convert any view to PDF using itextpdf.jar file. I will post my code here. This method will save the view in bitmap format.
public void saveViewImage(View view){
File file = saveBitMap(this, layout); //which view you want to pass that view as parameter
if (file != null) {
Log.i("TAG", "Drawing saved to the gallery!");
} else {
Log.i("TAG", "Oops! Image could not be saved.");
}
}
private File saveBitMap(Context context, View drawView){
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated)
Log.i("ATG", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
createPdf(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery( context,pictureFile.getAbsolutePath());
return pictureFile;
}
//create bitmap from view and returns it
private Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else{
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
Now the below method is used to generate the pdf
private void createPdf(Bitmap bitmap) throws IOException, DocumentException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image signature;
signature = Image.getInstance(stream.toByteArray());
signature.setAbsolutePosition(50f, 100f);
signature.scalePercent(60f);
//Image image = Image.getInstance(byteArray);
File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
if (!pdfFolder.exists()) {
pdfFolder.mkdirs();
Log.i("Created", "Pdf Directory created");
}
//Create time stamp
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
File myFile = new File(pdfFolder + timeStamp + ".pdf");
OutputStream output = new FileOutputStream(myFile);
//Step 1
Document document = new Document();
//Step 2
PdfWriter.getInstance(document, output);
//Step 3
document.open();
//Step 4 Add content
document.add(signature);
//document.add(new Paragraph(text.getText().toString()));
//document.add(new Paragraph(mBodyEditText.getText().toString()));
//Step 5: Close the document
document.close();
}

how to store a bitmap into internal storage in android

I know it's a very basic question but i am stuck to resolve this problem. I am working on image-sketching mobile app i have done all the work now I just want to store a resulting bitmap-image into internal memory.I have created a method "mageStore()" for image-storing purposes please write code there. I will be very thankful to you.
`private class ImageProcessingTask extends AsyncTask<Bitmap, Void, Bitmap> {
private ProgressDialog abhanDialog = null;
private Bitmap returnedBitmap = null;
#Override
protected void onPreExecute() {
returnedBitmap = null;
abhanDialog = new ProgressDialog(AbhanActivity.this);
abhanDialog.setMessage(getString(R.string.please_wait));
abhanDialog.setCancelable(false);
abhanDialog.show();
}
#Override
protected Bitmap doInBackground(Bitmap... params) {
final Bitmap sketched = AbhanSketch.createSketch(params[0]);
final Bitmap gaussianBitmap = AbhanEffects.applyGaussianBlur(sketched);
final Bitmap sepiaBitmap = AbhanEffects.sepiaTonnedBitmap(gaussianBitmap, 151, 0.71,
0.71, 0.76);
returnedBitmap = AbhanEffects.sharpenBitmap(sepiaBitmap, 0.81);
return returnedBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (abhanDialog != null && abhanDialog.isShowing()) {
abhanDialog.cancel();
}
if (result != null) {
mImageView.setImageBitmap(result);
mImageView.buildDrawingCache();
bmap = mImageView.getDrawingCache();
storeImage(bmap);
isImage = false;
enableButton();
final boolean isFileDeleted = Utils.deleteFile(mPath);
if (DEBUG) {
android.util.Log.i(TAG, "File Deleted: " + isFileDeleted);
}
}
}
}
private void storeImage(Bitmap image) {
...please enter code here for image storing
}`
Here is your missing code inside a function
private void storeImage(Bitmap image) {
File sdcard = Environment.getExternalStorageDirectory() ;
File folder = new File(sdcard.getAbsoluteFile(), "YOUR_APP_DIRECTORY");
if(!folder.exists())
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), "IMG_" + System.currentTimeMillis() + ".jpg") ;
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap = Bitmap.createScaledBitmap(bitmap, 400, (int) ( bitmap.getHeight() * (400.0 / bitmap.getWidth()) ) ,false);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You can omit or edit this line
bitmap = Bitmap.createScaledBitmap(bitmap, 400, (int) ( bitmap.getHeight() * (400.0 / bitmap.getWidth()) ) ,false);
according to your need.
in your function write the following code
String path = Saveme(image,"image_name.jpg");
//path contains the full path to directory where all your images get stored internaly lolz but privately
for gallery
Saveme(image,"my image","my image test for gallery save");
and the defination for the Saveme() function is following
private String Saveme(Bitmap bitmapImage, String img_name){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,img_name);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
in gallery images are displayed from media store so you need to store image in media store the following code can help you for this
public void Saveme(Bitmap b, String title, String dsc)
{
MediaStore.Images.Media.insertImage(getContentResolver(), b, title ,dsc);
}

Save view to image - location or not working

I'm trying to save my view as an image. I have done some work, doesn't show any error but I can find the location where is the image saved(or in the gallery). Is the image created at all, or I'm having some other issues? The image should be saved when pressing red from options menu:
case R.id.red:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String FILENAME="Boenka";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap( parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
parent.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return true;
This is my main - Draw class
public class Draw extends Activity {
DrawView drawView;
SignatureView signature;
private RelativeLayout parent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parent = (RelativeLayout) findViewById(R.id.signImageParent);
signature = new SignatureView(getApplicationContext(), null);
signature.setColor(Color.MAGENTA);
parent.addView(signature);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clear:
signature.clear();
return true;
case R.id.red:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String FILENAME="Boenka";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap( parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
parent.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return true;
case R.id.blue:
signature.setColor(Color.BLUE);
return true;
case R.id.yellow:
signature.setColor(Color.YELLOW);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
this.finish();
super.onBackPressed();
}
}
public void saveImage(Bitmap b,int count) throws Exception
{
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
String s=at.getText().toString();
String alphaAndDigits = s.replaceAll("[^a-zA-Z0-9]+","_");
String fileName = alphaAndDigits+"_"+wr.name+"_"+count;
File file = new File(path, fileName+".jpg");
newFile=Uri.fromFile(file);
uris.add(newFile);
fOut = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
Try this function it worked well for me, this is for saving the bitmap please ensure that drawing cache is working fine for you.
Try below code, it works
Add below permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
private DrawableView drawableView; //here I have taken customview, it is optional, I am saving this view as image. You can take any layout or view
private Button saveBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drawableView = (DrawableView) findViewById(R.id.drawable_view);
saveBtn = (Button) findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.save_btn:
File file = saveBitMap(this, drawableView); //which view you want to pass that view as parameter
if (file != null) {
Log.i("TAG", "Drawing saved to the gallery!");
} else {
Log.i("TAG", "Oops! Image could not be saved.");
}
break;
default:
break;
}
private File saveBitMap(Context context, View drawView){
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated)
Log.i("ATG", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery(pictureFile.getAbsolutePath(), context);
return pictureFile;
}
//create bitmap from view and returns it
private Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else{
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
// used for scanning gallery
private void scanGallery(Context cntx, String path) {
try {
MediaScannerConnection.scanFile(cntx, new String[] { path },null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

how take screen shot of currently playing video?

I'm trying to take a screenshot of the currently playing video. I'm trying with code that successfully takes a screenshot of web view but get not success in taking photo of currently playing video.
The code as follow for web view.
WebView w = new WebView(this);
w.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap( picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas( b );
picture.draw( c );
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/yahoo_" +System.currentTimeMillis() + ".jpg" );
if ( fos != null )
{
b.compress(Bitmap.CompressFormat.JPEG, 90, fos );
fos.close();
}
} catch( Exception e )
{
//...
}
}
});
setContentView( w );
w.loadUrl( "http://www.yahoo.com");
To expand on 66CLSjY's answer, FFmpegMediaMetadataRetriever has the same interface as MediaMetadataRetriever but it uses FFmpeg as the backend. If the default configuration won't work with your video format you can enable/disable codecs by recompiling. Here is some sample code:
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(mUri);
mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_VIDEO_CODEC);
Bitmap b = getFrameAtTime(3000);
mmr.release();
try this it will gives bitmap for your app screen
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
This works for me:
First a method to convert your view into a bitmap
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
Then save into the SD, for example:
static private boolean saveImage(Bitmap bm, String absolutePath)
{
FileOutputStream fos = null;
try
{
String absolutePath = "your path"
File file = new File(absolutePath);
fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fos); //PNG ignora la calidad
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fos != null)
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return true;
}
Good Luck!

Categories

Resources