- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试单击来自相机的图像并显示到 ImageView 中,但 onactivityresult URI 返回 null。但是下面的代码在 JellyBean 上运行良好,具有裁剪功能的 ICS。
调用 Intent
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
pickIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
String pickTitle = "Select or take a new Picture";
// startActivityForResult(captureIntent, 1);
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]
{ captureIntent });
startActivityForResult(chooserIntent, GlobalVariables.GALLERY_MODE);
onActivityResult
@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try
{
if (resultCode == RESULT_OK)
{
// user is returning from capturing an image using the camera
if (requestCode == GlobalVariables.GALLERY_MODE)
{
// get the Uri for the captured image
picUri = data.getData();
System.out.println("picUri ======= => "+picUri);
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat)
{
System.out.println(new GraphicsUtil().getPath(RegistrationActivity.this, picUri));
String filePath = new GraphicsUtil().getPath(RegistrationActivity.this, picUri);
System.out.println("filepath => "+filePath);
bitmapPreview = null;
bitmapPreview = BitmapFactory.decodeFile(filePath);
System.out.println("bitmapPreview => "+bitmapPreview );
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,
120, 120)));
}
else
{
performCrop(picUri, PIC_CROP, RegistrationActivity.this);
}
}
// user is returning from cropping the image
else if (requestCode == PIC_CROP)
{
String filePath = new File (Environment.getExternalStorageDirectory() + "/temporary_holder.jpg").getAbsolutePath();
bitmapPreview = null;
bitmapPreview = BitmapFactory.decodeFile(filePath);
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,
120, 120)));
// imageViewUser.setImageBitmap(new
// GraphicsUtil().getCircleBitmap(bitmapPreview));
File f = new File(Environment.getExternalStorageDirectory() + "/temporary_holder.jpg");
if (f.exists())
{
f.delete();
}
}
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
GraphicsUtil.java
public class GraphicsUtil
{
/*
* Draw image in circular shape Note: change the pixel size if you want
* image small or large
*/
public Bitmap getCircleBitmap(Bitmap bitmap)
{
Bitmap output;
Canvas canvas = null;
final int color = 0xffff0000;
final Paint paint = new Paint();
Rect rect = null;
if (bitmap.getHeight() > 501)
{
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
else
{
//System.out.println("output else =======");
bitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) 1);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public 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;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
@SuppressLint("NewApi")
public String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
在 android 4.4.2 操作系统上单击图像并选择图像时的 logcat 输出:-
05-08 17:25:55.697: I/System.out(20894): picUri ======= => null
05-08 17:25:55.698: W/System.err(20894): java.lang.NullPointerException
05-08 17:25:55.711: W/System.err(20894): at android.provider.DocumentsContract.isDocumentUri(DocumentsContract.java:587)
05-08 17:25:55.712: W/System.err(20894): at com.asiaelites.utils.GraphicsUtil.getPath(GraphicsUtil.java:119)
05-08 17:25:55.712: W/System.err(20894): at com.asiaelites.RegistrationActivity.onActivityResult(RegistrationActivity.java:489)
05-08 17:25:55.712: W/System.err(20894): at android.app.Activity.dispatchActivityResult(Activity.java:5446)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.deliverResults(ActivityThread.java:3442)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2802)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2274)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.access$800(ActivityThread.java:139)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
05-08 17:25:55.712: W/System.err(20894): at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 17:25:55.712: W/System.err(20894): at android.os.Looper.loop(Looper.java:136)
05-08 17:25:55.712: W/System.err(20894): at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 17:25:55.712: W/System.err(20894): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 17:25:55.713: W/System.err(20894): at java.lang.reflect.Method.invoke(Method.java:515)
05-08 17:25:55.713: W/System.err(20894): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 17:25:55.713: W/System.err(20894): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 17:25:55.713: W/System.err(20894): at dalvik.system.NativeStart.main(Native Method)
点击以下链接:-
Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT
最佳答案
这适用于 Kitkat
public class YourActivity extends Activity{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browsepicture);
imageView = (ImageView)findViewById(R.id.imageView1);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
if (Build.VERSION.SDK_INT < 19) {
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
imageView.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
}
For Cropping image
private void cropImage() {
// Use existing crop activity.
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(capturedImageUri, IMAGE_UNSPECIFIED);
// Specify image size
intent.putExtra("outputX", IMAGE_DIMENSION);
intent.putExtra("outputY", IMAGE_DIMENSION);
// Specify aspect ratio, 1:1
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
// REQUEST_CODE_CROP_PHOTO is an integer tag you defined to
// identify the activity in onActivityResult() when it returns
startActivityForResult(intent, REQ_CODE_CROP_PHOTO);
}
关于Android 4.4.2 - 相机 uri 返回 null 并且裁剪功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23541064/
是否有可能(在 cmd 批处理 ffmpeg 中)拍摄宽度已知(1920px)但高度未知的图像,如果超过,则将高度裁剪为特定的值?基本上是最大高度裁剪。 我玩过缩放和裁剪,但我无法得到我需要的结果。任
我有两个 SpatialPolygonsDataFrame文件:dat1、dat2 extent(dat1) class : Extent xmin : -180 xmax
我在 TensorFlow 上实现了全卷积网络。它使用编码器-解码器结构。训练时,我始终使用相同的图像大小(224x224,使用随机裁剪)并且一切正常。 在干扰阶段,我想一次预测一张图像,因为我想使用
我在 TensorFlow 上实现了全卷积网络。它使用编码器-解码器结构。训练时,我始终使用相同的图像大小(224x224,使用随机裁剪)并且一切正常。 在干扰阶段,我想一次预测一张图像,因为我想使用
我有一个需要裁剪的 View 。我有 4 个 View 显示在主视图上查看的视频 subview 。由于视频比例,我需要裁剪使视频成为正方形而不是矩形的 View 。这是我的代码: - (void)v
我正在构建一个使用 Parse 作为我的后端的网络应用程序。 部分注册过程涉及用户上传和裁剪图片,然后我将其传递到我的数据库(图片是用户个人资料的一部分,类似于您在 Twitter 上所做的)。 我已
我正在制作一个基于立方体的游戏(一切都是立方体),目前正在尝试通过不在视野之外绘制东西来优化它。 以下内容仅适用于 x 和 y 平面,稍后我会担心 z ......所以现在只进行侧面裁剪。 我知道我自
我正在尝试在 iOS 上实现单指图像缩放/裁剪。类似于柯比·特纳的单指旋转。我正在寻找现有的库,或者如果您可以帮助我处理代码本身,那就太好了。 最佳答案 我不太清楚你所说的一指裁剪是什么意思,但我为
从这里: http://www.kylejlarson.com/blog/2011/how-to-create-pie-charts-with-css3/ .pieContainer
我已经设置了一个 SKScene 用作 SKReferenceNode。雪橇是一个 SKSpriteNode,在引用节点场景中定义了一个自定义类,所有的狗都是雪橇 Sprite 的 child 。自定
我有一个库,其中包含一些图像处理算法,包括感兴趣区域(裁剪)算法。使用 GCC 编译时,自动矢量化器会加速很多代码,但会降低 Crop 算法的性能。是否有标记某个循环以被矢量化器忽略的方法,或者是否有
代码位于 http://jsfiddle.net/rSSXu/ Child #parent { margin-left:auto; margin-right:auto;
我搜索了很多以删除不需要的空间,但找不到。我只找到可用于删除黑白背景空间的链接。但我的背景图片可以是任何东西。所以,如果我有这些图片, 我如何提取我需要的图像部分。例如, 最佳答案 这是我对你的问题的
我正在尝试将 CMSampleBufferRef 中的图像裁剪为特定大小。我正在执行 5 个步骤 - 1. 从 SampleBuffer 获取 PixelBuffer 2. 将 PixelBuffer
我读到它是自动的,但在我的案例中似乎没有发生。使用 UIImagePickerController 并将 allowsEditing 设置为 YES 我得到了带有裁剪方形叠加层的编辑 View ,但是
我正在寻找一种高效的方法来裁剪二维数组。考虑这个例子: 我有一个构成 100x100 网格的二维数组。我只想返回其中的一部分,60x60。这是一个“a”方法的示例,但我正在寻找指向执行此操作的最高性能
我有一个接受 UIImage 的类,用它初始化一个 CIImage,如下所示: workingImage = CIImage.init(image: baseImage!) 然后使用图像以 3x3 的
我正在尝试显示来自 mysql 数据库的图像。有些图像显示正确,但有些图像在底部显示为剪切/裁剪,裁剪部分仅显示为空白,当它成为图像的一部分时,您真的无法摆脱。 CSS 无法解决这个问题,使用 ima
我有个问题。我有什么理由不应该使用这个 Intent: Intent intent = new Intent("com.android.camera.action.CROP"); 为了裁剪我刚刚拍摄的
我有一些代码可以调整图像大小,因此我可以获得图像中心的缩放 block - 我使用它来获取 UIImage 并返回一个小的方形表示图片,类似于在照片应用程序的相册 View 中看到的内容。 (我知道我
我是一名优秀的程序员,十分优秀!