繁体   English   中英

Android 检测图像是来自网络的 png/jpg/etc 扩展名

[英]Android detect the image is png/jpg/etc extension from the web

我必须从我的网站上读取图像。 但是,用户在服务器中上传的图像具有多种扩展名。 jpg png 等我如何修改image_url代码以自动检测图像的扩展名而不必将其声明为静态

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_product, container, false);

    // Loader image - will be shown before loading image
    int loader = R.drawable.loader;

    editTxtQuantity = (EditText)rootView.findViewById(R.id.inputQuantity);

    btnAddtocart = (Button) rootView.findViewById(R.id.btnAddtocart);
    btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
    productErrorMsg = (TextView) rootView.findViewById(R.id.product_error);

    txtName = (TextView) rootView.findViewById(R.id.inputName);
    txtPrice = (TextView) rootView.findViewById(R.id.inputPrice);
    txtDesc = (TextView) rootView.findViewById(R.id.inputDesc);

    // Imageview to show
    image = (ImageView) rootView.findViewById(R.id.image);

    // Getting productid from ScanFragment
    pid = getArguments().getString("pid");

    // Image url
    String image_url = "http://smartqr.droid-addict.com/upload/products/" + pid +".png"; 

    // ImageLoader class instance
    ImageLoader imgLoader = new ImageLoader(getActivity().getApplicationContext());

    // whenever you want to load an image from url
    // call DisplayImage function
    // url - image url to load
    // loader - loader image, will be displayed before getting image
    // image - ImageView 
    imgLoader.DisplayImage(image_url, loader, image);

这是因为图像文件的名称不是固定的。 那么如何正确显示图像及其正确的扩展名。

您只需使用String .endsWith(....)方法检查Image_url.png结尾

if(image_url.endsWith(".png")){
//your image ends with .png

}else if(image_url.endsWith(".jpg")){
//your image  ends with .jpg
}

您可以使用String.endsWith方法这样做,请参阅链接以更好地理解。

String image_url = "http://testing-123.com/upload/products/" + pid +".png";

if(image_url.endsWith("png"))
{
  // do something
}
else if(image_url.endsWith("jpg"))
{
  // do something
}
else if(image_url.endsWith("bmp"))
{
  // do something
}

希望它会帮助你。

这是最好的方法,如果您从设备中选择图像。

...

 /*
     * Get the file's content URI from the incoming Intent, then
     * get the file's MIME type
     */


Uri returnUri = returnIntent.getData();

String mimeType = getContentResolver().getType(returnUri);

https://developer.android.com/training/secure-file-sharing/retrieve-info#java ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM