I can rake pictures from this code but i am not able to save the pictures into custom directory Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
and i think this is probably the line where i have to change my code
want to make a custom directory and save my image there
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,
"waH kiAa selfie hAi :D ",
//+ uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
Try this approach...
private void saveImage(byte[] arg0) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "YOUR_CUSTOM_FOLDER";
File myDir = new File(root);
myDir.mkdirs();
String fname = "YOUR_IMAGE_NAME" + ".jpg";
file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Bitmap bitmap1 = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
FileOutputStream out;
try {
out = new FileOutputStream(file);
bitmap1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap1, "", "");
}
Related
This question already has answers here:
How I can convert a bitmap into PDF format in android [closed]
(3 answers)
Closed 2 months ago.
I am trying to convert an activity to pdf format.I have taken a screenshot of the same as a bitmap.PLease help me to convert that sreenshot to the required pdf file.Thank you.
Please provide the code.Thank you.
This is the code I used...
1) MainActivity
public class MainActivity extends Activity {
//Button btn_getpdf;
private LinearLayout linearLayout;
private Bitmap myBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btn_getpdf = (Button) findViewById(R.id.button_pdf);
linearLayout = (LinearLayout) findViewById(R.id.linear1);
linearLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(linearLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if (myBitmap != null) {
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if (v != null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
} catch (Exception e) {
// Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public void saveImage(Bitmap bitmap) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(root.getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
}
2)WritePdfActivity
public class WritePdfActivity extends Activity
{
private static String FILE ="DCIM/Camera/GenPdf.pdf";
static Image image;
static ImageView img;
Bitmap bmp;
static Bitmap bt;
static byte[] bArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView)findViewById(R.id.imageView1);
try
{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addImage(document);
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void addImage(DocumentsContract.Document document)
{
try
{
image = Image.getInstance(bArray); ///Here i set byte array..you can do bitmap to byte array and set in image...
}
catch (BadElementException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// image.scaleAbsolute(150f, 150f);
try
{
document.add(image);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Plz try this So question:
How I can convert a bitmap into PDF format in android
pdf-format-in-android/14393561#14393561
or also include itextpdf-5.3.2.jar in your project
#Swagatam Dutta use
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera/bitmap.jpg");
I couldn't find the solution for my issue. My MainActivity creates a pdf file, the user adds some text via EditText and closes it, no problem with that. Then I have a secondary activity that is calling the MediaStore.ACTION_IMAGE_CAPTURE to take pictures. Once a picture is taken, I'd like to know how I can get this just-captured image into that pdf.
I know I have to reopen the pdf, that is no problem, since I have the pdf file name saved in a variable. The major problem that I see is that I don't know how to programmatically get the file name of the picture, once it is automatically named after "yyyyMMdd_hhMMss.jpg". So how to get the file name from a picture taken by my secondary activity?
*EDIT - Showing code:
From MainActivity:
public class MainActivity extends Activity {
public String FILE = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
public static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
public static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
public static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
EditText estRep;
EditText sensRep;
EditText cabRep;
String estais;
String sensores;
String cabos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
estRep = (EditText)findViewById(R.id.estaisRep);
sensRep = (EditText)findViewById(R.id.sensoresRep);
cabRep = (EditText)findViewById(R.id.cabosRep);
}
public void gerarPDF(View view) {
estais = estRep.getText().toString();
sensores = sensRep.getText().toString();
cabos = cabRep.getText().toString();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("CoManut");
alertDialog.setMessage("Picture?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
startActivity(intent);
}
});
alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Thanks for using this app!", Toast.LENGTH_LONG).show();
MainActivity.this.finish();
}
});
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.show();
}
private static void addMetaData(Document document) {
document.addTitle("Image and text to PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Ricardo Gramowski");
document.addCreator("Ricardo Gramowski");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
preface.add(new Paragraph("Maintenance report", catFont));
addEmptyLine(preface, 1);
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("This doc is important", smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph("This doc has been generated by Gramowski.",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("Chapter 1", catFont);
anchor.setName("Chapter 1");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Results", subFont);
Section subCatPart = catPart.addSection(subPara);
addEmptyLine(subPara, 1);
createTable(subCatPart);
document.add(catPart);
}
private void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(2);
PdfPCell c1 = new PdfPCell(new Phrase("Item"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Is that good? (OK/Not OK)"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("Estais da Torrre ");
table.addCell(estais);
table.addCell("Sensores ");
table.addCell(sensores);
table.addCell("Cabos ");
table.addCell(cabos);
subCatPart.add(table);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
And my PhotoActivity:
public class PhotoActivity extends ActionBarActivity {
Button b1;
ImageView iv;
Bitmap bp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
b1 = (Button) findViewById(R.id.button1);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
// Button to go back to the MainActivity
public void onclickButton2(View view) {
PhotoActivity.this.finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Override your onActivitResult() method in your Main Activity
Here you will get the image bitmap from (Intent Data)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
Now you have the bitmap. You can add bitmap image like below using the iText Library
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // Try with Bitmap.CompressFormat.JPG also
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
}catch(IOException ex){
ex.printStackTrace();
}
Update1
Your onActivityResult() should look like this.
Note Make sure you have WRITE_EXTERNAL_STORAGE permissions in your menifest.xml file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
This will create a sample.pdf file in your sdcard and add Image bitmap into it.
Hope this helps.
I tested it here its working. :)
I have implemented a save button in my ImagePagerActivity however it crashes when i click the save button.
Please point out any errors I might be causing unaware or if there's another way of saving the images more effectively to the sd card. I am still a newbie to coding so please double check my work.
ImagePagerActivity.java
.....
Button isave;
isave = (Button) findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap mSaveBit = imageLoader.getMemoryCache().get(Constants.IMAGES[pager.getCurrentItem()]);
File imageFile = null;
if (null == mSaveBit) {
imageFile = imageLoader.getDiscCache().get(Constants.IMAGES[pager.getCurrentItem()]);
}
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
if (!f.exists()) {
f.mkdirs();
}
f = new File(f.getAbsolutePath(),
String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
mSaveBit.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(ImagePagerActivity.this, "Image Successfully Saved", Toast.LENGTH_LONG).show();
}
});
.....
i want save my picture in a folder that i choose; i have the following code that save in default folder images of my dispositive; how can i modify this code for my app?
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(FotoActivity.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
add this code to your onPictureTaken
Date now = new Date();
long nowLong = now.getTime() / 9000;
String fname = getPhotoDirectory(MyclassName.this)+"/"+nowLong+".jpg";
String why = "";
try {
File ld = new File(getPhotoDirectory(MyclassName.this));
if (ld.exists()) {
if (!ld.isDirectory()){
MyclassName.this.finish();
}
} else {
ld.mkdir();
}
Log.d(TAG, "open output stream "+fname +" : " +data.length);
OutputStream os = new FileOutputStream(fname);
os.write(data,0,data.length);
os.close();
} catch (FileNotFoundException ex0) {
why = ex0.toString();
ex0.printStackTrace();
} catch (IOException ex1) {
why = ex1.toString();
ex1.printStackTrace();
}
add this method in your class
public static String getPhotoDirectory(Context context)
{
//return Environment.getExternalStorageDirectory().getPath() +"/cbo-up";
return context.getExternalFilesDir(null).getPath() +"/cbo-up";
}
i have bitmap image when return result and then i want to save it in Photo Art Camera folder in SD card but it is not saved. it shows the toast "Photo Not Saved Sucessfully".
This is the code:
mSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
File cacheDir;
Bitmap bitmap = result;
// String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Date d = new Date();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "Photo Art Camera");
} else { cacheDir = MainActivity.this.getCacheDir(); }
if (!cacheDir.exists()) { cacheDir.mkdirs(); }
File file = new File(cacheDir, "PhotoMarge" + d.getTime() + ".jpg");
try {
fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 150, fOut);
// getImageBitmap(myurl).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
Toast.makeText(MainActivity.this, "Photo Saved Sucessfully", 500).show();
// mDialog.dismiss();
// MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Photo Not Saved Sucessfully", 500).show();
}
}
});
i removed my misstake from code .Actually i am saving another bitmap instead saving and converting framelayout bitmap
File cacheDir;
frame.setDrawingCacheEnabled(true);
icon = Bitmap.createBitmap(frame.getDrawingCache());
Bitmap bitmap = icon;
// String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Date d=new Date();
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Photo Art Camera");
else
cacheDir=MainActivity.this.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
File file = new File(cacheDir, "PhotoMarge"+d.getTime()+".jpg");
try {
fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fOut);
//getImageBitmap(myurl).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
count();
Toast.makeText(MainActivity.this, "Photo Saved Sucessfully", 500).show();
// mDialog.dismiss();
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "Photo Not Saved Sucessfully", 500).show();
}
}
});
you are compressing it with different argument make it to 100 or 120 it should work..
OutputStream fOut = new FileOutputStream(output);
merged.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
OR
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
save22.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File cacheDir;
Toast.makeText(Main.this, "Photo", 500)
.show();
Bitmap icon;
relativelayout.setDrawingCacheEnabled(true);
icon = Bitmap.createBitmap(relativelayout.getDrawingCache());
Bitmap bitmap = icon;
relativelayout.setDrawingCacheEnabled(false);
//File mFile1 = Environment.getExternalStorageDirectory();
Date d=new Date();
String fileName = d.getTime()+"mg1.jpg";
File storagePath = (Environment
.getExternalStorageDirectory());
File dest = new File(storagePath + "/CityAppImages");
if (!dest.exists()) {
dest.mkdirs();
}
File mFile2 = new File(dest, fileName);
sdpath= mFile2.getAbsolutePath();
Log.d("qqqqqqqqqqqqqqqqqqqqqqq", "zzzzzzzz" + sdpath);
try {
FileOutputStream outStream;
outStream = new FileOutputStream(mFile2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(Main.this, "Photo Saved Sucessfully", 500)
.show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Main.this, "Photo Not Saved Sucessfully",
500).show();
}