I am trying to take the output of the captured image into a uri but it throws null pointer exception on another component which was not null before and when not storing the image in uri it runs okay
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"Photo" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap temp=null;
Bundle extras = data.getExtras();
/*Uri g=data.getData();
try {
temp = MediaStore.Images.Media.getBitmap(getContentResolver(), g);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
int h=photo.getHeight();
int w=photo.getWidth();
/* try {
temp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri1);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmapdata = stream.toByteArray();
Log.i("image", ""+bitmapdata);
image_boolean=true;
stream.flush();
stream.close();
/*File f = new File(mImageCaptureUri1.getPath());
if (f.exists()) f.delete();*/
}catch(Exception e)
{}
imageView.setImageBitmap(photo);
}}
}
Related
I am taking a photo with the camera and saving the photo value into a bitmap. I would like to use that photo in itext to generate an pdf.
This is the code I have so far.
Bitmap bitmap;
public void Picture()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap=(Bitmap)data.getExtras().get("data");
PDF();
}
public void PDF()
{
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Image img = Image.getInstance(bitmap);
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Example"));
document.close();
}
bitmap=(Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
Image maimg = Image.getInstance(stream3.toByteArray());
maimg.setAbsolutePosition(490, 745);
maimg.scalePercent(40);
document.add(maimg);
you should download itextpdf-5.3.2.jar file and attach in your project.
You can use it as an example:
public class WritePdfActivity extends Activity
{
private static String FILE = "mnt/sdcard/FirstPdf.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(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();
}
}
}
Here is the reference, Please check
enter link description here
One Important thing better to use PDFBox library for convert Image to PDF
Im trying to capture image and then for good practice I put bitmap file in the the FileOutputStream how can I recover the bitmap using the filename.
Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == REQUEST_CODE_CAMERA && data != null){
fragment = null;
Bitmap bmp = (Bitmap) data.getExtras().get("data");
String filename = "bitmap.png";
try {
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
stream.close();
bmp.recycle();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left,R.anim.fade_out,R.anim.fade_in,R.anim.slide_out_right);
fragment =FragmentCropper.newInstance(filename);
fragmentTransaction.add(R.id.fragmentContainer,fragment,Constant.BackStackTag.CROP_TAG);
fragmentTransaction.addToBackStack(Constant.BackStackTag.CROP_TAG);
fragmentTransaction.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the Fragment
How to recover the Bitmap using the filename
try {
//FileInputStream stream = getActivity().openFileInput(filename);
//mBitmap = BitmapFactory.decodeStream(stream);
//stream.close();
String path = "path/"+filename;
mBitmap = BitmapUtils.decodeSampledBitmapFromFile(path,500,500);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (mBitmap.isRecycled())
mBitmap.recycle();
mBitmap=null;
}
String path = "path/"+filename;
Change to
String path = getFilesDir().getAbsolutePath() + "/" + filename;
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 am working on a application in which there a part of taking images
from camera and have to share images to the different applications . I am using a code but it is not sharing the images. please have a look and please tell where I am wrong.
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Am trying to decode the multiple barcodes found on the image which is picked from the gallery,
but its not returning any data about the barcodes. Here is the my code snippet....
the following code picks the image from gallery and tries to decode them.
please suggest me the best way that i can succeed my requirements.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap bMap = BitmapFactory.decodeFile(selectedImagePath);
LuminanceSource source = new RGBLuminanceSource(bMap);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
try {
Result result = reader.decode(bitmap);
Global.text = result.getText();
byte[] rawBytes = result.getRawBytes();
BarcodeFormat format = result.getBarcodeFormat();
ResultPoint[] points = result.getResultPoints();
tv1.setText(Global.text);
tv2.setText("FORMAT: " + format);
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ChecksumException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}