Wado.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Copyright (c) 2012-2020 fo-dicom contributors.
  2. // Licensed under the Microsoft Public License (MS-PL).
  3. using System;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Http.Headers;
  12. using System.Threading.Tasks;
  13. using System.Web.Http;
  14. using System.Web.Http.Cors;
  15. using Dicom;
  16. using Dicom.Imaging;
  17. using Dicom.Imaging.Codec;
  18. using Dicom.IO;
  19. using Wado.Models;
  20. namespace Wado.Controllers
  21. {
  22. /// <summary>
  23. /// main controller for wado implementation
  24. /// </summary>
  25. /// <remarks>the current implementation is incomplete</remarks>
  26. /// <remarks>more infos in the official specification : http://dicom.nema.org/medical/dicom/current/output/pdf/part18.pdf </remarks>
  27. [EnableCors(origins: "*", headers: "*", methods: "GET")] //allows access by any host
  28. [RoutePrefix("wado")]
  29. public class WadoUriController : ApiController
  30. {
  31. #region consts
  32. /// <summary>
  33. /// string representation of the dicom content type
  34. /// </summary>
  35. private const string AppDicomContentType = "application/dicom";
  36. /// <summary>
  37. /// string representation of the jpeg content type
  38. /// </summary>
  39. private const string JpegImageContentType = "image/jpeg";
  40. #endregion
  41. #region fields
  42. /// <summary>
  43. /// service used to retrieve images by instance Uid
  44. /// </summary>
  45. private readonly IDicomImageFinderService _dicomImageFinderService;
  46. #endregion
  47. #region constructors
  48. /// <summary>
  49. /// Initialize a new instance of WadoUriController
  50. /// </summary>
  51. public WadoUriController()
  52. {
  53. //Put your own IDicomImageFinderService implementation here for real world scenarios
  54. _dicomImageFinderService = new TestDicomImageFinderService();
  55. }
  56. /// <summary>
  57. /// Testing purposes constructor if you want to inject a custom IDicomImageFinderService
  58. /// in unit tests
  59. /// </summary>
  60. /// <param name="dicomImageFinderService"></param>
  61. public WadoUriController(IDicomImageFinderService dicomImageFinderService)
  62. {
  63. _dicomImageFinderService = dicomImageFinderService;
  64. }
  65. #endregion
  66. #region methods
  67. /// <summary>
  68. /// main wado method
  69. /// </summary>
  70. /// <param name="requestMessage">web request</param>
  71. /// <param name="requestType">always equals to wado in current wado specification, may change in the future</param>
  72. /// <param name="studyUID">study instance UID</param>
  73. /// <param name="seriesUID">serie instance UID</param>
  74. /// <param name="objectUID">instance UID</param>
  75. /// <param name="contentType">The value shall be a list of MIME types, separated by a "," character, and potentially associated with relative degree of preference, as specified in IETF RFC2616. </param>
  76. /// <param name="charset">character set of the object to be retrieved.</param>
  77. /// <param name="transferSyntax">The Transfer Syntax to be used within the DICOM image object, as specified in PS 3.6</param>
  78. /// <param name="anonymize">if value is "yes", indicates that we should anonymize object.
  79. /// The Server may return an error if it either cannot or refuses to anonymize that object</param>
  80. /// <returns></returns>
  81. [Route("")]
  82. public async Task<HttpResponseMessage> GetStudyInstances(HttpRequestMessage requestMessage, string requestType,
  83. string studyUID, string seriesUID, string objectUID, string contentType = null, string charset = null,
  84. string transferSyntax = null, string anonymize = null)
  85. {
  86. //we do not handle anonymization
  87. if (anonymize == "yes")
  88. return requestMessage.CreateErrorResponse(HttpStatusCode.NotAcceptable, "anonymise is not supported on the server");
  89. //we extract the content types from contentType value
  90. bool canParseContentTypeParameter = ExtractContentTypesFromContentTypeParameter(contentType,
  91. out string[] contentTypes);
  92. if (!canParseContentTypeParameter)
  93. return requestMessage.CreateErrorResponse(HttpStatusCode.NotAcceptable,
  94. string.Format("contentType parameter (value: {0}) cannot be parsed", contentType));
  95. //8.1.5 The Web Client shall provide list of content types it supports in the "Accept" field of the GET method. The
  96. //value of the contentType parameter of the request shall be one of the values specified in that field.
  97. string[] acceptContentTypesHeader =
  98. requestMessage.Headers.Accept.Select(header => header.MediaType).ToArray();
  99. // */* means that we accept everything for the content Header
  100. bool acceptAllTypesInAcceptHeader = acceptContentTypesHeader.Contains("*/*");
  101. bool isRequestedContentTypeCompatibleWithAcceptContentHeader = acceptAllTypesInAcceptHeader ||
  102. contentTypes == null ||
  103. acceptContentTypesHeader.Intersect(
  104. contentTypes).Any();
  105. if (!isRequestedContentTypeCompatibleWithAcceptContentHeader)
  106. {
  107. return requestMessage.CreateErrorResponse(HttpStatusCode.NotAcceptable,
  108. string.Format("content type {0} is not compatible with types specified in Accept Header",
  109. contentType));
  110. }
  111. //6.3.2.1 The MIME type shall be one on the MIME types defined in the contentType parameter, preferably the most
  112. //desired by the Web Client, and shall be in any case compatible with the ‘Accept’ field of the GET method.
  113. //Note: The HTTP behavior is that an error (406 – Not Acceptable) is returned if the required content type cannot
  114. //be served.
  115. string[] compatibleContentTypesByOrderOfPreference =
  116. GetCompatibleContentTypesByOrderOfPreference(contentTypes,
  117. acceptContentTypesHeader);
  118. //if there is no type that can be handled by our server, we return an error
  119. if (compatibleContentTypesByOrderOfPreference != null
  120. && !compatibleContentTypesByOrderOfPreference.Contains(JpegImageContentType)
  121. && !compatibleContentTypesByOrderOfPreference.Contains(AppDicomContentType))
  122. {
  123. return requestMessage.CreateErrorResponse(HttpStatusCode.NotAcceptable,
  124. string.Format("content type(s) {0} cannot be served",
  125. string.Join(" - ", compatibleContentTypesByOrderOfPreference)
  126. ));
  127. }
  128. //we now need to handle the case where contentType is not specified, but in this case, the default value
  129. //depends on the image, so we need to open it
  130. string dicomImagePath = _dicomImageFinderService.GetImageByInstanceUid(objectUID);
  131. if (dicomImagePath == null)
  132. {
  133. return requestMessage.CreateErrorResponse(HttpStatusCode.NotFound, "no image found");
  134. }
  135. try
  136. {
  137. IOManager.SetImplementation(DesktopIOManager.Instance);
  138. DicomFile dicomFile = await DicomFile.OpenAsync(dicomImagePath);
  139. string finalContentType = PickFinalContentType(compatibleContentTypesByOrderOfPreference, dicomFile);
  140. return ReturnImageAsHttpResponse(dicomFile,
  141. finalContentType, transferSyntax);
  142. }
  143. catch (Exception ex)
  144. {
  145. Trace.TraceError("exception when sending image: " + ex.ToString());
  146. return requestMessage.CreateErrorResponse(HttpStatusCode.InternalServerError, "server internal error");
  147. }
  148. }
  149. /// <summary>
  150. /// returns dicomFile in the content type given by finalContentType in a HttpResponseMessage.
  151. /// If content type is dicom, transfer syntax must be set to the given transferSyntax parameter.
  152. /// </summary>
  153. /// <param name="dicomFile"></param>
  154. /// <param name="finalContentType"></param>
  155. /// <param name="transferSyntax"></param>
  156. /// <returns></returns>
  157. private HttpResponseMessage ReturnImageAsHttpResponse(DicomFile dicomFile, string finalContentType, string transferSyntax)
  158. {
  159. MediaTypeHeaderValue header = null;
  160. Stream streamContent = null;
  161. if (finalContentType == JpegImageContentType)
  162. {
  163. DicomImage image = new DicomImage(dicomFile.Dataset);
  164. Bitmap bmp = image.RenderImage(0).As<Bitmap>();
  165. //When an image/jpeg MIME type is returned, the image shall be encoded using the JPEG baseline lossy 8
  166. //bit Huffman encoded non-hierarchical non-sequential process ISO/IEC 10918.
  167. //TODO Is it the case with default Jpeg format from Bitmap?
  168. header = new MediaTypeHeaderValue(JpegImageContentType);
  169. streamContent = new MemoryStream();
  170. bmp.Save(streamContent, ImageFormat.Jpeg);
  171. streamContent.Seek(0, SeekOrigin.Begin);
  172. }
  173. else if (finalContentType == AppDicomContentType)
  174. {
  175. //By default, the transfer syntax shall be
  176. //"Explicit VR Little Endian".
  177. //Note: This implies that retrieved images are sent un-compressed by default.
  178. DicomTransferSyntax requestedTransferSyntax = DicomTransferSyntax.ExplicitVRLittleEndian;
  179. if (transferSyntax != null)
  180. requestedTransferSyntax = GetTransferSyntaxFromString(transferSyntax);
  181. bool transferSyntaxIsTheSameAsSourceFile =
  182. dicomFile.FileMetaInfo.TransferSyntax == requestedTransferSyntax;
  183. //we only change transfer syntax if we need to
  184. DicomFile dicomFileToStream;
  185. if (!transferSyntaxIsTheSameAsSourceFile)
  186. {
  187. dicomFileToStream = dicomFile.Clone(requestedTransferSyntax);
  188. }
  189. else
  190. {
  191. dicomFileToStream = dicomFile;
  192. }
  193. header = new MediaTypeHeaderValue(AppDicomContentType);
  194. streamContent = new MemoryStream();
  195. dicomFileToStream.Save(streamContent);
  196. streamContent.Seek(0, SeekOrigin.Begin);
  197. }
  198. var result = new HttpResponseMessage(HttpStatusCode.OK)
  199. {
  200. Content = new StreamContent(streamContent)
  201. };
  202. result.Content.Headers.ContentType = header;
  203. return result;
  204. }
  205. /// <summary>
  206. /// Choose the final content type given compatibleContentTypesByOrderOfPreference and dicomFile
  207. /// </summary>
  208. /// <param name="compatibleContentTypesByOrderOfPreference"></param>
  209. /// <param name="dicomFile"></param>
  210. /// <returns></returns>
  211. private static string PickFinalContentType(string[] compatibleContentTypesByOrderOfPreference, DicomFile dicomFile)
  212. {
  213. int nbFrames = dicomFile.Dataset.GetSingleValue<int>(DicomTag.NumberOfFrames);
  214. //if compatibleContentTypesByOrderOfPreference is null,
  215. //it means we must choose a default content type based on image content:
  216. // *Single Frame Image Objects
  217. // If the contentType parameter is not present in the request, the response shall contain an image/jpeg MIME
  218. // type, if compatible with the ‘Accept’ field of the GET method.
  219. // *Multi Frame Image Objects
  220. // If the contentType parameter is not present in the request, the response shall contain a application/dicom
  221. // MIME type.
  222. //not sure if this is how we distinguish multi frame objects?
  223. bool isMultiFrame = nbFrames > 1;
  224. bool chooseDefaultValue = compatibleContentTypesByOrderOfPreference == null;
  225. string chosenContentType;
  226. if (chooseDefaultValue)
  227. {
  228. if (isMultiFrame)
  229. {
  230. chosenContentType = AppDicomContentType;
  231. }
  232. else
  233. {
  234. chosenContentType = JpegImageContentType;
  235. }
  236. }
  237. else
  238. {
  239. //we need to take the compatible one
  240. chosenContentType = compatibleContentTypesByOrderOfPreference
  241. .Intersect(new[] { AppDicomContentType, JpegImageContentType })
  242. .First();
  243. }
  244. return chosenContentType;
  245. }
  246. /// <summary>
  247. /// extract content type values (may have multiple values according to IETF RFC2616)
  248. /// </summary>
  249. /// <param name="contentType">contentype string from wado request</param>
  250. /// <param name="contentTypes">extracted content types</param>
  251. /// <returns>false if there is a parse error, else true</returns>
  252. private static bool ExtractContentTypesFromContentTypeParameter(string contentType, out string[] contentTypes)
  253. {
  254. //8.1.5 MIME type of the response
  255. //The value shall be a list of MIME types, separated by a "," character, and potentially associated with
  256. //relative degree of preference, as specified in IETF RFC2616.
  257. //so we must split the string
  258. contentTypes = null;
  259. if (contentType != null && contentType.Contains(","))
  260. {
  261. contentTypes = contentType.Split(',');
  262. }
  263. else if (contentType == null)
  264. {
  265. contentTypes = null;
  266. }
  267. else
  268. {
  269. contentTypes = new[] {contentType};
  270. }
  271. //we now need to parse each type which follows the RFC2616 syntax
  272. //it also extracts parameters like jpeg quality but we discard it because we don't need them for now
  273. try
  274. {
  275. if (contentType != null)
  276. {
  277. contentTypes =
  278. contentTypes.Select(contentTypeString => MediaTypeHeaderValue.Parse(contentTypeString))
  279. .Select(mediaTypeHeader => mediaTypeHeader.MediaType).ToArray();
  280. }
  281. }
  282. catch (FormatException)
  283. {
  284. {
  285. return false;
  286. }
  287. }
  288. return true;
  289. }
  290. /// <summary>
  291. /// Get the compatible content types from the Accept Header, by order of preference
  292. /// </summary>
  293. /// <param name="contentTypes"></param>
  294. /// <param name="acceptContentTypesHeader"></param>
  295. /// <returns>
  296. /// compatible types by order of preference
  297. /// if contentTypes==null, returns null
  298. /// </returns>
  299. private static string[] GetCompatibleContentTypesByOrderOfPreference(
  300. string[] contentTypes, string[] acceptContentTypesHeader)
  301. {
  302. //je vérifie tout d'abord que parmis les types demandés, il y en a bien un que je gère.
  303. //je dois prendre l'intersection des types demandés et acceptés et les trier par ordre de préférence
  304. bool acceptAllTypesInAcceptHeader = acceptContentTypesHeader.Contains("*/*");
  305. string[] compatibleContentTypesByOrderOfPreference;
  306. if (acceptAllTypesInAcceptHeader)
  307. {
  308. compatibleContentTypesByOrderOfPreference = contentTypes;
  309. }
  310. //null represent the default value
  311. else if (contentTypes == null)
  312. {
  313. compatibleContentTypesByOrderOfPreference = null;
  314. }
  315. else
  316. {
  317. //intersect should preserve order (so it's already sorted by order of preference)
  318. compatibleContentTypesByOrderOfPreference = acceptContentTypesHeader.Intersect(contentTypes).ToArray();
  319. }
  320. return compatibleContentTypesByOrderOfPreference;
  321. }
  322. /// <summary>
  323. /// Converts string dicom transfert syntax to DicomTransferSyntax enumeration
  324. /// </summary>
  325. /// <param name="transferSyntax"></param>
  326. /// <returns></returns>
  327. private DicomTransferSyntax GetTransferSyntaxFromString(string transferSyntax)
  328. {
  329. try
  330. {
  331. return DicomParseable.Parse<DicomTransferSyntax>(transferSyntax);
  332. }
  333. catch (Exception)
  334. {
  335. //if we have an error, this probably means syntax is not supported
  336. //so according to 8.2.11 in spec, we use default ExplicitVRLittleEndian
  337. return DicomTransferSyntax.ExplicitVRLittleEndian;
  338. }
  339. }
  340. #endregion
  341. }
  342. }