Is it possible to add an image to the PDF document? My layout has one (Button) and one (ImageView), I would like that when I click (Button), it will open the Gallery to select the image, show it in (ImageView) and add it to the PDF document, as if it were a generator curriculum, thank you in advance.
*Using com.itextpdf:itextg:5.5.10
here is the complete code of what you wanted. Try this and let me know.
In the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_to_pdf);
imageView = findViewById(R.id.imageView);
galleryBtn = findViewById(R.id.gallery);
convertBtn = findViewById(R.id.convert);
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "PDF_" + timeStamp + "_";
File storageDir = getAlbumDir();
try {
pdfPath = File.createTempFile(
imageFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, GALLERY_INTENT);
}
});
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
} else {
convertToPDF(pdfPath);
}
}
});
}
Create a directory for PDF file:
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "Image to pdf");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
On camera activity intent result:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
cursor.close();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Canceled", "Image not selected");
}
}
}
Now code to convert image to PDF and save to the directory:
private void convertToPDF(File pdfPath) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(pdfPath));
Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}
Related
I have made the following focus effect for Xamarin.Forms.Android so when the keyboard is focused on the element it shows blue rectangle around it.:
protected override void OnAttached()
{
try
{
OriginalBackground = Container.Background;
if(Control != null)
{
Control.FocusChange += Control_FocusChange;
}
else
{
Container.FocusChange += Control_FocusChange;
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
}
private void Control_FocusChange(object sender, FocusChangeEventArgs e)
{
if(Control != null)
{
if (Control.HasFocus)
{
Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
Control.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Control.SetBackground(OriginalBackground);
}
}
else
{
if (Container.HasFocus)
{
Container.SetBackgroundColor(Android.Graphics.Color.Red);
Container.SetBackgroundResource(Resource.Drawable.focusFrame);
}
else
{
Container.SetBackground(OriginalBackground);
}
}
}
Can someone tell me how to the same effect for Xamarin.Forms.IOS ? I tried the following code but it doesn't work on focusing the app the same way as Android. Somehow there isn't an event or perhaps I am missing it for IOS:
UIColor backgroundColor;
UIView view;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
try
{
OriginalBackground = Container.GetBackgroundLayer;
if (Container != null)
{
this.Container.DidUpdateFocus()
CreateRectange();
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
private void CreateRectange()
{
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(30, 100, 36, 36);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(18.0, 18.0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Black.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Red.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
Container.AddSubview(view);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
At first, the frame's size should fit the control. And then you need to set the maskLayer.FillColor as UIColor.Clear.CGColor to make the control's content will show correctly.
You can try the following code:
UIView view;
float width,height;
public Func<Brush, CALayer> OriginalBackground { get; private set; }
protected override void OnAttached()
{
}
private void CreateRectange()
{
height = (float)Control.Frame.Height;
width = (float)Control.Frame.Width;
view = new UIView();
view.BackgroundColor = UIColor.Clear;
view.Frame = new CGRect(0,0,width,height);
var maskLayer = new CAShapeLayer();
UIBezierPath bezierPath = UIBezierPath.FromRoundedRect(view.Bounds, (UIRectCorner.TopLeft | UIRectCorner.BottomLeft), new CGSize(0,0));
maskLayer.Path = bezierPath.CGPath;
maskLayer.Frame = view.Bounds;
maskLayer.StrokeColor = UIColor.Red.CGColor; //set the borderColor
maskLayer.FillColor = UIColor.Clear.CGColor; //set the background color
maskLayer.LineWidth = 1; //set the border width
view.Layer.AddSublayer(maskLayer);
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
try
{
if (args.PropertyName == "IsFocused")
{
CreateRectange();
Control.AddSubview(view);
}
}
catch (Exception ex)
{
Console.WriteLine("Cannot set property on attached control. Error: ", ex.Message);
}
}
I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}
I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}
My requirement is to take picture from the camera or pick a image from the gallery and show it in a image view.. After showing the image I'm sending as a mail whatever the image is selected. My issues is every time i take a portrait picture form the camera it rotates and show it in the image view. How to fix this issue.
thanks in advance.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.skicka_bild_activity);
share = new Sharedprefs(SkickaBild.this);
emailSendButton = (Button) findViewById(R.id.skicka_button);
emailSendButton.setOnClickListener(this);
emailSendButton.setEnabled(false);
Button camaraOnButtton = (Button) findViewById(R.id.fotografera_button);
camaraOnButtton.setOnClickListener(this);
Button galleryOpenButton = (Button) findViewById(R.id.valj_bild_button);
galleryOpenButton.setOnClickListener(this);
imageSetImageView = (ImageView) findViewById(R.id.imageView_skick);
maxWidth = share.getmaxwidth();
mContentResolver = getContentResolver();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.skicka_button:
if (isImageViewFilled) {
showEmailComposer();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
SkickaBild.this);
builder.setTitle("Alert !!");
builder.setMessage("Pick a image before you send the email")
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
break;
case R.id.fotografera_button:
share.setisFromTabsClearImage(false);
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent takePictureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
startActivityForResult(takePictureIntent, 0);
break;
case R.id.valj_bild_button:
share.setisFromTabsClearImage(false);
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(mCapturedImageURI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
Bitmap mImageBitmap = BitmapFactory
.decodeFile(capturedImageFilePath);
imageSetImageView.setImageBitmap(mImageBitmap);
isImageViewFilled = true;
if (isImageViewFilled) {
emailSendButton.setEnabled(true);
emailSendButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.skicka_button_black));
}
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
System.out.println("PICTURE PATH " + capturedImageFilePath);
pic = new File(capturedImageFilePath);
String cPath = pic.getAbsolutePath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cPath, bmOptions);
float photoW = mImageBitmap.getWidth();
float photoH = mImageBitmap.getHeight();
// Get the dimensions of the View
float targetW = Float.parseFloat(maxWidth);
float targetH = (photoH / photoW) * targetW;
System.out.println("cam bitmap height"
+ mImageBitmap.getHeight());
System.out.println("cam bitmap weidth" + maxWidth);
System.out.println("cam bitmap Width 02 "
+ mImageBitmap.getWidth());
System.out.println("cam target Height " + targetH);
System.out.println("cam target width " + targetW);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = (int) scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(cPath, bmOptions);
mImageBitmap = Bitmap.createScaledBitmap(bitmap,
(int) targetW, (int) targetH, false);
FileOutputStream fout;
try {
fout = new FileOutputStream(pic);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
fout);
fout.flush();
fout.close();
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream in = null;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
System.out.println("PICTUREPATH" + picturePath);
cursor.close();
Bitmap imageBitmap = BitmapFactory.decodeFile(picturePath);
int orientation = getOrientation(this, selectedImage);
System.out.println("ORIENTATION VALUE " + orientation);
imageSetImageView.setImageBitmap(imageBitmap);
isImageViewFilled = true;
if (isImageViewFilled) {
emailSendButton.setEnabled(true);
emailSendButton.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.skicka_button_black));
}
// ////////////////////////// Image is set ///////////////
pic = new File(picturePath);
String cPath = pic.getAbsolutePath();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cPath, bmOptions);
float photoW = imageBitmap.getWidth();
float photoH = imageBitmap.getHeight();
// Get the dimensions of the View
float targetW = Float.parseFloat(maxWidth);
float targetH = (photoH / photoW) * targetW;
System.out.println(" bitmap height"
+ imageBitmap.getHeight());
System.out.println(" bitmap weidth" + maxWidth);
System.out.println(" bitmap Width 02 "
+ imageBitmap.getWidth());
System.out.println(" target Height " + targetH);
System.out.println(" target width " + targetW);
float scaleFactor = Math.min(photoW / targetW, photoH
/ targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = (int) scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(cPath, bmOptions);
imageBitmap = Bitmap.createScaledBitmap(bitmap,
(int) targetW, (int) targetH, false);
FileOutputStream fout;
fout = new FileOutputStream(pic);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
public static int getOrientation(Context context, Uri photoUri) {
String[] orientationColumn = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = context.getContentResolver().query(photoUri,
orientationColumn, null, null, null);
try {
if (cursor.moveToFirst()) {
return cursor.getInt(cursor
.getColumnIndex(orientationColumn[0]));
} else {
return -1;
}
} finally {
cursor.close();
}
}
private void showEmailComposer() {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { share.getMailTo() });
email.putExtra(Intent.EXTRA_SUBJECT, share.getsubject());
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
// email.putExtra(Intent.EXTRA_STREAM, pic.getName());
email.putExtra(Intent.EXTRA_TEXT, share.getemailbody());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
isEmailSend = true;
}
#Override
protected void onResume() {
super.onResume();
System.out.println("ON RESUME INCOMING CHECK");
if (share.getisFromTabsClearImage()) {
imageSetImageView.setImageDrawable(getResources().getDrawable(
R.drawable.ingenbildvald));
emailSendButton.setBackgroundDrawable(getResources().getDrawable(
R.drawable.skicka_button));
emailSendButton.setEnabled(false);
share.setisFromTabsClearImage(false);
}
if (isEmailSend) {
imageSetImageView.setImageDrawable(getResources().getDrawable(
R.drawable.ingenbildvald));
emailSendButton.setBackgroundDrawable(getResources().getDrawable(
R.drawable.skicka_button));
emailSendButton.setEnabled(false);
isEmailSend = false;
}
}
I am having Images stored in SD Card and using that images i wish to run an animation. I am using the following code for this but my animation is not working at all.
Code Snippet
playAnimation("xxx", medid, 25);//calling method
break;
public void playAnimation(String string, int medid2, int length) {
// TODO Auto-generated method stub
animation = new AnimationDrawable();
Bitmap bitMap;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
player = MediaPlayer.create(this.getApplicationContext(), medid2);
try {
for (int i = 0; i <= length; i++) {
System.out.println("File Name : - " + Environment.getExternalStorageDirectory().toString() + "/" + string + i);
bitMap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + "/" + string + i);
Drawable bmp = new BitmapDrawable(bitMap);
animation.addFrame(bmp, DURATION);
}
animation.setOneShot(true);
animation.setVisible(true, true);
int frames = animation.getNumberOfFrames();
System.out.println("Number of Frames are - " + frames);
img.setBackgroundDrawable(animation);
img.post(new Starter());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
class Starter implements Runnable {
public void run() {
try {
if(animation.isRunning()) {
animation.stop();
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
} else {
animation.start();
if (player.isPlaying()) {
player.stop();
player.start();
}
else {
player.start();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Using concept of Frame Animation i need to run my animation. I am able fetch images as i have done some debugging but when i click on button and this methods are called my screen is not displaying any animation. It just display black screen only. I am not getting any error in this. If anyone having idea please kindly let me know.
Thanks
An AnimationDrawable just shows black screen, may be caused by different reasons. For example, in the Android Dev Guide, Drawable Animation, the following code lets you load a series of Drawable resources.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}
However, if you set resource after getBackground() like the following code, the screen will keep black.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
}
If you want to load images from SD card, and show them as animation, you can refer to the following code. I write and test on API 8 (2.3).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showedImage = (ImageView) findViewById(R.id.imageView_showedPic);
showedImage.setBackgroundResource(R.drawable.slides);
frameAnimation = (AnimationDrawable) showedImage.getBackground();
addPicturesOnExternalStorageIfExist();
}
#Override
public void onWindowFocusChanged (boolean hasFocus){
super.onWindowFocusChanged (hasFocus);
frameAnimation.start();
}
private void addPicturesOnExternalStorageIfExist() {
// check if external storage
String state = Environment.getExternalStorageState();
if ( !(Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) ) {
return;
}
// check if a directory named as this application
File rootPath = Environment.getExternalStorageDirectory();
// 'happyShow' is the name of directory
File pictureDirectory = new File(rootPath, "happyShow");
if ( !pictureDirectory.exists() ) {
Log.d("Activity", "NoFoundExternalDirectory");
return;
}
// check if there is any picture
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".jpeg") ||
name.endsWith(".jpg") ||
name.endsWith(".png") );
}
};
String[] sNamelist = pictureDirectory.list(filefilter);
if (sNamelist.length == 0) {
Log.d("Activity", "No pictures in directory.");
return;
}
for (String filename : sNamelist) {
Log.d("Activity", pictureDirectory.getPath() + '/' + filename);
frameAnimation.addFrame(
Drawable.createFromPath(pictureDirectory.getPath() + '/' + filename),
DURATION);
}
return;
}