How to retrieve an image from memory card in this scenario - android-canvas

i am saving an image by passing a bitmap to the savephoto(Bitmap function)
now i want to retrieve the photo which is saved ,, how to do that i am new in android , plz give me the code of retrival and also convert it into Bitmap
public void savePhoto(Bitmap b2)
{
File imageFileFolder = new File(Environment.getExternalStorageDirectory(),"Rotate");
mageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
File imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try
{
out = new FileOutputStream(imageFileName);
b2.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
out = null;
} catch (Exception e)
{
e.printStackTrace();
}
thanx helping :)

Related

File provider error to receive pdf from another program

`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6
` #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int ExtractImage(Intent intent) {
try {
String filepath = null;
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
filepath = file_uri.getPath();
}
} else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null) {
filepath = uri.getPath();
}
}
}
File file = new File(filepath);
PdfRenderer renderer = null;
Bitmap bm;
try {
renderer = new PdfRenderer(ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
}
assert renderer != null;
final int pageCount = renderer.getPageCount();
totalPage = pageCount;
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
// Create a bitmap and canvas to draw the page into
int width = 570;
int zarib = 570 / (page.getWidth() + 1);
int height = (page.getHeight() * 2) + 1;
heightArray.add(i, height);
// Create a bitmap and canvas to draw the page into
bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create canvas to draw into the bitmap
Canvas c = new Canvas(bm);
// Fill the bitmap with a white background
Paint whiteBgnd = new Paint();
whiteBgnd.setColor(Color.WHITE);
whiteBgnd.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, width, height, whiteBgnd);
// paint the page into the canvas
page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
// Save the bitmap
OutputStream outStream = null;
try {
outStream = new
FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/printDo2ta" + i + ".png");
} catch (Exception e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
page.close();
}
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(getBaseContext(),
"خطا در پردازش فایل: " + e.getMessage(),
Toast.LENGTH_SHORT).show());
}
return totalPage;
}
I inserted this code in AndroidManifest.xml
`<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.myproject.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>`
`
And I made the class provider_paths.xml
`<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>`
I don't know what else I need to change to make it work on Android 8
please help me`

iTextSharp Document Isn't Working After Deployment

i'm using iTextSharp to create a pdf document then add it as an attachment to send an email using SendGrid.
The code is working locally but after deploying the project in Azure this function stopped working for some reason. I tried to analyze the problem and i think that the document didn't fully created of attached due to the connection. I can't pin point the exact issue to solve it. Any opinions or discussion is appreciated.
Action:
public async Task<IActionResult> GeneratePDF(int? id, string recipientEmail)
{
//if id valid
if (id == null)
{
return NotFound();
}
var story = await _db.Stories.Include(s => s.Child).Include(s => s.Sentences).ThenInclude(s => s.Image).FirstOrDefaultAsync(s => s.Id == id);
if (story == null)
{
return NotFound();
}
var webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "dump"); //folder name
try
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
string usedFont = Path.Combine(webRootPath + "\\fonts\\", "arial.TTF");
BaseFont bf = BaseFont.CreateFont(usedFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(bf, 40);
iTextSharp.text.Font sentencesFont = new iTextSharp.text.Font(bf, 15);
iTextSharp.text.Font childNamewFont = new iTextSharp.text.Font(bf, 35);
PdfPTable T = new PdfPTable(1);
//Hide the table border
T.DefaultCell.BorderWidth = 0;
T.DefaultCell.HorizontalAlignment = 1;
T.DefaultCell.PaddingTop = 15;
T.DefaultCell.PaddingBottom = 15;
//Set RTL mode
T.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
//Add our text
if (story.Title != null)
{
T.AddCell(new iTextSharp.text.Paragraph(story.Title, titleFont));
}
if (story.Child != null)
{
if (story.Child.FirstName != null && story.Child.LastName != null)
{
T.AddCell(new iTextSharp.text.Phrase(story.Child.FirstName + story.Child.LastName, childNamewFont));
}
}
if (story.Sentences != null)
{
.................
}
document.Add(T);
writer.CloseStream = false;
document.Close();
byte[] bytes = memoryStream.ToArray();
var fileName = path + "\\PDF" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
memoryStream.Position = 0;
memoryStream.Close();
//Send generated pdf as attchment
// Create the file attachment for this email message.
var attachment = Convert.ToBase64String(bytes);
var client = new SendGridClient(Options.SendGridKey);
var msg = new SendGridMessage();
msg.From = new EmailAddress(SD.DefaultEmail, SD.DefaultEmail);
msg.Subject = story.Title;
msg.PlainTextContent = "................";
msg.HtmlContent = "..................";
msg.AddTo(new EmailAddress(recipientEmail));
msg.AddAttachment("Story.pdf", attachment);
try
{
await client.SendEmailAsync(msg);
}
catch (Exception ex)
{
Console.WriteLine("{0} First exception caught.", ex);
}
//Remove form root
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
}
}
catch (FileNotFoundException e)
{
Console.WriteLine($"The file was not found: '{e}'");
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine($"The directory was not found: '{e}'");
}
catch (IOException e)
{
Console.WriteLine($"The file could not be opened: '{e}'");
}
return RedirectToAction("Details", new { id = id });
}
try to edit usedfont variable as bellow :
var usedfont = Path.Combine(webRootPath ,#"\fonts\arial.TTF")
It turns out that the problem is far from iTextSharp. I did a remote debugging from this article.
Two parts of the code was causing the problem.
First, for some reason the folder "dump" was not created on Azure wwwroot folder while locally it is. so, i added these lines:
var webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "dump");
if (!Directory.Exists(path)) //Here
Directory.CreateDirectory(path);
Second, after debugging it shows that creating the file was failing every time. I replaced the following lines:
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
memoryStream.Position = 0;
memoryStream.Close();
With:
using (FileStream fs = new FileStream(fileName, FileMode.Create))
using (var binaryWriter = new BinaryWriter(fs))
{
binaryWriter.Write(bytes, 0, bytes.Length);
binaryWriter.Close();
}
memoryStream.Close();
Hope this post helps someone.

Why are results in the browser using Google AutoML so different from an exported tflite file in my android app?

I'm training a model using Google AutoML. I then exported a TFLite model to run on an android app.
With the same image used in the app and in the browser (Google AutoML gives you a chance to test your model in the browser), I get a very accurate answer in the browser but in my app, I get a not-so accurate answer.
Any thoughts on why this could be happening?
Relevant code:
public void predict(String imagePath, final Promise promise) {
imgData.order(ByteOrder.nativeOrder());
labelProbArray = new byte[1][RESULTS_TO_SHOW];
try {
labelList = loadLabelList();
} catch (Exception ex) {
ex.printStackTrace();
}
Log.w("FIND_ ", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
convertBitmapToByteBuffer(bitmap);
try {
tflite = new Interpreter(loadModelFile());
} catch (Exception ex) {
Log.w("FIND_exception in loading tflite", "1");
}
tflite.run(imgData, labelProbArray);
promise.resolve(getResult());
}
private WritableNativeArray getResult() {
WritableNativeArray result = new WritableNativeArray();
//ArrayList<JSONObject> result = new ArrayList<JSONObject>();
try {
for (int i = 0; i < RESULTS_TO_SHOW; i++) {
WritableNativeMap map = new WritableNativeMap();
map.putString("label", Integer.toString(i));
float output = (float)(labelProbArray[0][i] & 0xFF) / 255f;
map.putString("prob", String.valueOf(output));
result.pushMap(map);
Log.w("FIND_label ", Integer.toString(i));
Log.w("FIND_prob ", String.valueOf(labelProbArray[0][i]));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private List<String> loadLabelList() throws IOException {
Activity activity = getCurrentActivity();
List<String> labelList = new ArrayList<String>();
BufferedReader reader =
new BufferedReader(new InputStreamReader(activity.getAssets().open(LABEL_PATH)));
String line;
while ((line = reader.readLine()) != null) {
labelList.add(line);
}
reader.close();
return labelList;
}
private void convertBitmapToByteBuffer(Bitmap bitmap) {
if (imgData == null) {
return;
}
imgData.rewind();
Log.w("FIND_bitmap width ", String.valueOf(bitmap.getWidth()));
Log.w("FIND_bitmap height ", String.valueOf(bitmap.getHeight()));
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the image to floating point.
int pixel = 0;
//long startTime = SystemClock.uptimeMillis();
for (int i = 0; i < DIM_IMG_SIZE_X; ++i) {
for (int j = 0; j < DIM_IMG_SIZE_Y; ++j) {
final int val = intValues[pixel++];
imgData.put((byte) ( ((val >> 16) & 0xFF)));
imgData.put((byte) ( ((val >> 8) & 0xFF)));
imgData.put((byte) ( (val & 0xFF)));
Log.w("FIND_i", String.valueOf(i));
Log.w("FIND_j", String.valueOf(j));
}
}
}
private MappedByteBuffer loadModelFile() throws IOException {
Activity activity = getCurrentActivity();
AssetFileDescriptor fileDescriptor = activity.getAssets().openFd(MODEL_PATH);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
One of the things I don't know if is correct is how I adjust my output data into a probability. In the getResult() method, I write this:
float output = (float)(labelProbArray[0][i] & 0xFF) / 255f;
I divide by 255 in order to get a number between 0 and 1, but I don't know if this is correct.
The .tflite model is a quantized uint8 model if that helps.

ArrayList Double

Im getting this error
java.lang.NumberFormatException: Invalid double: "-20.528899,"
im using a webservice to get latitude and longitude from bd, and show in a map.
I am not able to pass the latitude and longitude values to list
i am saving lat and long at the same column in db, so this field should be "lat, long" eg "-20.528899, -47.438933" and i need to parse this in the list...can i do this?
public List<Localizacoes> buscarLocalizacoes(){
List<Localizacoes> lista = new ArrayList<Localizacoes>();
SoapObject buscarLocalizacoes = new SoapObject(NAMESPACE, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarLocalizacoes);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("uri:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta){
Localizacoes loc = new Localizacoes();
loc.setId(Integer.parseInt(soapObject.getProperty("id").toString()));
loc.setNome(soapObject.getProperty("nome").toString());
loc.setDescricao(soapObject.getProperty("descricao").toString());
loc.setPosicao(soapObject.getProperty("posicao").toString()); // error in this line
lista.add(loc);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return lista;
}
activity
dao = new LocalizacoesDAO(context);
List<Localizacoes> lista = dao.buscarLocalizacoes();
Log.d("Teste Buscar", lista.toString());
public void setPosicao(LatLng poLatLng) {
this.poLatLng = poLatLng;
this.posicao = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
public void setPosicao(String posicao) {
this.posicao = posicao;
String[] pos = posicao.split(" ");
this.poLatLng = new LatLng(Double.valueOf(pos[0]), Double.valueOf(pos[1]));
}
can anyone help me pls?
Change the following line in your setPosicao(String) method
String[] pos = posicao.split(" ");
INTO
String[] pos = posicao.split(", ");
(Since you have a ',' and a ' ' in the string)

Adding JPG to PDF extremely slow

I'm trying to write an Image to PDF using PDFBox. I'm using their sample (as attached). Everything is fine, but writing 3.5MB jpeg (3200*2500px) takes roughly 2 seconds.
Is this normal ? Is there any way how to make it faster (at least 10x) ?
public void createPDFFromImage( String inputFile, String image, String outputFile )
throws IOException, COSVisitorException
{
// the document
PDDocument doc = null;
try
{
doc = PDDocument.load( inputFile );
//we will add the image to the first page.
PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
//BufferedImage awtImage = ImageIO.read( new File( image ) );
//ximage = new PDPixelMap(doc, awtImage);
throw new IOException( "Image type not supported:" + image );
}
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.drawImage( ximage, 20, 20 );
contentStream.close();
doc.save( outputFile );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
If you are willing to use another product itext could go really fast, take a look at http://tutorials.jenkov.com/java-itext/image.html .Personally, I did this test with a +750k jpg image and took 78 ms
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image2.pdf"));
document.open();
long start = System.currentTimeMillis();
String imageUrl = "c:/Users/dummy/notSoBigImage.jpg";
Image image = Image.getInstance((imageUrl));
image.setAbsolutePosition(500f, 650f);
document.add(image);
document.close();
long end = System.currentTimeMillis() - start;
System.out.println("time: " + end + " ms");
} catch(Exception e){
e.printStackTrace();
}