大家好,当我尝试选择一个图像配置文件,如果我尝试从相机上传照片一切正常,但如果我从画廊上传照片我没有显示任何东西。打开图库并选择照片的功能有效但在选择了照片后她应该出现但没有出现任何内容。 希望你帮帮我。谢谢。 这是代码:
public class UpdateProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView imgProfile;
Button btnSaveProfile,btnMyadd;
EditText edtName,edtEmail,edtNumber,edtWebsite;
TextView txtname,txtEmail,txtNumber,txtWebsite;
ProgressDialog progressBar;
String name,email,number,website;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
File file;
boolean isphotoselected = false;
private SharedPreferences pref;
Typeface typeface;
String advertId,advertUserName,advertPassword,advertEmail,advertPhone,advertSite,advertImage;
boolean AddFlag= false;
MarshMallowPermission marshMallowPermission;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_updateprofile);
toolbar = (Toolbar) findViewById(R.id.toolbar);
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
if (toolbar != null) {
toolbar.setTitle("Profile Update");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
marshMallowPermission = new MarshMallowPermission(this);
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
}
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
imgProfile = (ImageView)findViewById(R.id.imgProfile);
btnMyadd = (Button)findViewById(R.id.btnMyadd);
btnSaveProfile=(Button)findViewById(R.id.btnSaveprofile);
edtEmail = (EditText)findViewById(R.id.edtEmailid);
edtName = (EditText)findViewById(R.id.edtName);
edtNumber = (EditText)findViewById(R.id.edtphone);
edtWebsite= (EditText)findViewById(R.id.edtwebsite);
txtEmail = (TextView)findViewById(R.id.txtEmail);
txtname = (TextView)findViewById(R.id.txtName);
txtNumber = (TextView)findViewById(R.id.txtPhone);
txtWebsite= (TextView)findViewById(R.id.txtWeb);
btnMyadd.setTypeface(typeface);
btnSaveProfile.setTypeface(typeface);
edtEmail.setTypeface(typeface);
edtName.setTypeface(typeface);
edtNumber.setTypeface(typeface);
edtWebsite.setTypeface(typeface);
txtEmail.setTypeface(typeface);
txtname.setTypeface(typeface);
txtNumber.setTypeface(typeface);
txtWebsite.setTypeface(typeface);
pref = getSharedPreferences("loginpreference", MODE_PRIVATE);
imgProfile.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startDialog();
}
});
btnSaveProfile.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
name = edtName.getText().toString();
number = edtNumber.getText().toString();
email = edtEmail.getText().toString();
website= edtWebsite.getText().toString();
boolean flag = emailValidator(email);
if(name.equalsIgnoreCase("")){
edtName.setError("Please Enter Name");
}else if(number.equalsIgnoreCase("")){
edtNumber.setError("Please Enter Contact Number");
}else if(flag == false){
edtEmail.setError("Please Enter Email");
}else if(website.equalsIgnoreCase("")){
edtWebsite.setError("Please Enter Website");
}else if(selectedImagePath.equalsIgnoreCase("") || selectedImagePath==null){
Toast.makeText(getApplicationContext(), "Please Select Profile Picture", Toast.LENGTH_SHORT).show();
}else {
new UpdateProfileTask().execute();
}
}
});
btnMyadd.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!AddFlag){
Toast.makeText(UpdateProfileActivity.this, "Please Update Your Profile", Toast.LENGTH_SHORT).show();
}else{
AddFlag = true;
Intent intent =new Intent(UpdateProfileActivity.this, MyAdsActivity.class);
intent.putExtra("advertId", advertId);
startActivity(intent);
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
public boolean emailValidator(String s)
{
return Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$").matcher(s).matches();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class UpdateProfileTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd= new CustomProgressDialog();
@Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(UpdateProfileActivity.this, "Loading...");
}
@Override
protected Void doInBackground(Void... arg0) {
jsonStr = uploadFile();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String responce = jsonObj.getString(Constants.LOGIN_TAG);
String msg = jsonObj.getString(Constants.REG_TAG);
if(responce.equalsIgnoreCase("success")){
JSONArray jArray = jsonObj.getJSONArray("data");
if(jArray.length()>0){
JSONObject j1 = jArray.getJSONObject(0);
advertId = j1.getString("advertId");
advertUserName = j1.getString("advertUserName");
advertPassword = j1.getString("advertPassword");
advertEmail = j1.getString("advertEmail");
advertPhone = j1.getString("advertPhone");
advertSite = j1.getString("advertSite");
advertImage = j1.getString("advertImage");
AddFlag = true;
}
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(UpdateProfileActivity.this, msg, Toast.LENGTH_SHORT).show();
}
edtEmail.setText("");
edtName.setText("");
edtNumber.setText("");
edtWebsite.setText("");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.WEBURL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
}
});
if(isphotoselected){
file = new File(selectedImagePath);
//entity.addPart("userfile",selectedImagePath.toString();
entity.addPart("avtar", new FileBody(file));
//entity.addPart("filesArray[]",new FileBody(file));
isphotoselected = false;
}
String advartid = pref.getString("advertId", "");
entity.addPart("action", new StringBody("updateAccount"));
entity.addPart("advertId", new StringBody(advartid));
entity.addPart("username", new StringBody(name));
entity.addPart("email", new StringBody(email));
entity.addPart("phone", new StringBody(number));
entity.addPart("site", new StringBody(website));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE)
onSelectFromGalleryResult(data);
else if (requestCode == CAPTURE_IMAGE)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
//onCaptureFromCamera
private void onCaptureImageResult(Intent data) {
beginCrop(data.getData());
}
//onSelectFromGalleryResult()
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
使用此方法处理裁剪:
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
//save to internal storage
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
//read from storage
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
//inside onResume
@Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
private void startDialog()
{
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Upload Pictures Option");
builder.setMessage("How do you want to set your picture?");
builder.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""),PICK_IMAGE);
}
});
builder.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
builder.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
将此添加到build.gradle依赖项:
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
}
然后将其添加到您的AndroidManifest文件中:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
答案 0 :(得分:0)
试试这个:
由于您已完成从图库中选择:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
}
现在,方法onSelectFromGalleryResult(data)
:
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
beginCrop(selectedImageUri);
}
如果要裁剪图像,
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = handleSamplingAndRotationBitmap(this, Crop.getOutput(result));
saveToInternalStorage(bitmap);
mUserProfilePhoto.setImageBitmap(readFromInternalStorage("profile.png"));
}catch (IOException e){ /* do nothing here */}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
然后,如果您需要自动旋转,
private static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage) throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Bitmap img, Uri selectedImage) throws IOException {
ExifInterface ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
要将图像保存在设备内部存储中:
private boolean saveToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("profile.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
从存储中读取:
private Bitmap readFromInternalStorage(String filename){
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
return BitmapFactory.decodeStream(fi);
} catch (Exception ex) { /* do nothing here */}
return null;
}
设置ImageView:
@Override
public void onResume(){
super.onResume();
Bitmap savedProfilePhoto = readFromInternalStorage("profile.png");
if (savedProfilePhoto != null){
mUserProfilePhoto.setImageBitmap(savedProfilePhoto);
}
}
要完成任务,如果要添加裁剪,
几乎在这里完成:
将此添加到您的依赖项(build.gradle)
dependencies{
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
}
最后,在您的Android清单文件中,要使裁剪库工作,请添加:
<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>
这就是您在应用程序内使用相机从图库中选择图像或拍照时所需的一切!